Showing posts with label PHP. Show all posts
Showing posts with label PHP. Show all posts

PHP Browser Redirect

Posted by Muhammad Shiraz Kamboh Wednesday, 13 June 2012 0 comments
It is an simple example which will take the visitors to one page if they are using Internet Explorer, and to another page if the visitor is using another type of browser.
Now lets decide what is going to happen if:
  1. If the browser is Microsoft Internet Explorer (MSIE), it will automatically redirect to: www.tutorialize.org/redirect1 ( example )
  2. If the browser is not Microsoft Internet Explorer (MSIE), it will automatically redirect to: www.tutorialize.org/redirect2( example )
The most interesting part of this is that this code is, that it has to be sent out before any output to the HTML page. You will have to make sure that the code is filled under the first line of code on your PHP page.
This is the example php code, it can be modified in many ways to fill your requests.
 
//if its MSIE then
if ($name = strstr ($HTTP_USER_AGENT, "MSIE"))
{
   //it will send to www.tutorialize.org/redirect1
   Header ("Location: http://www.tutorialize.org/redirect1");
}
else
{
   //else will send to www.tutorialize.org/redirect2
   Header ("Location: http://www.yahoo.com/");
}

Simple PHP Form Mail Tutorial

Posted by Muhammad Shiraz Kamboh Tuesday, 12 June 2012 0 comments
Simple mail form
 
This tutorial will show you how to create a simple form mail that emails a specified email.
The Following Code is the actual form where the input can be typed.






Create HTML Form in Seconds

Posted by Muhammad Shiraz Kamboh Monday, 28 May 2012 0 comments
Create Online Simple awesome HTML Form with easy 3 Steps


Click Here to 
Create PHP, HTML Form


Sending emails in PHP & email injection attacks

Posted by Muhammad Shiraz Kamboh Sunday, 27 May 2012 0 comments

PHP’s inbuilt mail() function provides very limited mail functionality. Although its easy to send text emails, but thats pretty much the only thing you can do with it. If you need extended functionality like HTML emails or attachments, you can always go through a couple of hundred pages of mail specifications at IETF .
Or you can stop trying to reinvent the wheel and use existing PHP mail libraries. Two such excellent libraries are:
  1. PHPMailer
  2. Swift Mailer
PHPMailer has been around for a long time is definitely more popular and well known but its development seems to have petered out. There has been no new releases since July 2005.
Swift Mailer on the other hand is relatively new and is more actively developed. Both websites have enough documentation and examples to get you started.
PHPMailer offers no protection against header injections. I wasn’t sure about the Swift Mailer since I don’t have much experience with it. So I put the question to Chris Corbyn, Swift Mailer’s developer. Below is his response:
Characters outside the 7-bit printable ASCII range are encoded into a 7-bit format making them incapable of affecting the header structure.
So I guess that this another reason for choosing Swift Mailer.

Email injection or mail form spamming

Spammers can hijack your seemingly innocuous looking mail form to send out spam. They do so by posting specially formatted data to your mail script. This is known as email injection or mail form spamming.
Below is the PHP code to send a simple HTML email using the mail() function.
$to = 'recipient@somedomain.xxx';
$from = 'sender@anotherdomain.xxx';
$fromname = 'Dilbert';
$subject = 'HTML Email';
$headers = "Date: ".date('r')."\n";
$headers .= "Return-Path: ".$from."\n";
$headers .= "From: ".$fromname."\n";
$headers .= "Message-ID: <".md5(uniqid(time()))."@anotherdomain.xxx>\n";
$headers .= "X-Priority: 3\n";
$headers .= "MIME-Version: 1.0\n";
$headers .= "Content-Transfer-Encoding: 8bit\n";
$headers .= 'Content-Type: text/html; charset="iso-8859-1"'."\n";
$body ='

HTML Email Body

';
mail($to, $subject, $body, $headers);
If the you run the above script (after substituting the recipient and sender email addresses) you will receive a HTML email in your inbox. Everything fine so far. Now change the value of the $from variable to the following:
$from = "sender@anotherdomain.xxx
Cc:victim@domain2.xxx";
Run the script again and you will see that two emails are sent out this time. One to the recipient@somedomain.xxx and the second to victim@domain2.xxx . This is a simplified version of mail header injection attack but the basic methodology is the same. The spammers will try to inject headers into your mail script using newlines and carriage returns.
Most often than not, variables like $from and $subject are populated by data received from a form, thus leaving the door open for possible mail injection attacks. The least you should do is to strip newlines (\n) and carriage returns (\r).

Protection against email injections and mail form spamming

As mentioned earlier, you can prevent email header injections by removing the newlines and carriage returns from the incoming data. You can use the below two functions to protect your script.
Both the functions are essentially the same. The only difference is in their usage. The first function will replace the newlines and carriage returns. The second function is a validation function which returns true if it finds newlines or carriage returns in the passed string.
function heal($str) {
 $injections = array('/(\n+)/i',
 '/(\r+)/i',
 '/(\t+)/i',
 '/(%0A+)/i',
 '/(%0D+)/i',
 '/(%08+)/i',
 '/(%09+)/i'
 );
 $str= preg_replace($injections,'',$str);
 return $str;
}
function isInjected($str) {
 $injections = array('(\n+)',
 '(\r+)',
 '(\t+)',
 '(%0A+)',
 '(%0D+)',
 '(%08+)',
 '(%09+)'
 );
 $inject = join('|', $injections);
 $inject = "/$inject/i";
 if(preg_match($inject,$str)) {
  return true;
 }
 else {
  return false;
 }
}
You can use the second function to display an error to the spammer. But it would be better to send a “403 Forbidden” or “404 Page Not Found” headers rather than to display an insulting message. The spammer just might decide to take you on your challenge.

PHP MySQL Basics Tutorial

Posted by Muhammad Shiraz Kamboh 0 comments

PHP and MySql are the most common and popular combination you would come across on the Internet. Affordable Linux hosting, open source nature of these two technologies and the freedom from expensive proprietary licenses are the main reasons for the success of this combination.

Connecting to MySQL through PHP

To connect to a mysql database server, use the following function:



$link = mysql_connect($hostname, $username, $password, $newlink);
A call to mysql_connect returns a link identifier on success or FALSE on failure. Lets go through the arguments one at a time:
$hostname = The domain name of the mysql server. If both the web server and mysql are located on the same machine/computer, you can simply use “localhost”.
$username = Login ID/username of the mysql server
$password = Password for the mysql server
The fourth argument ($newlink) is not used very often and you can skip it in most cases. mysql_connect either opens a new connection to the mysql server or uses an existing connection. Calling mysql_connect multiple times will return the same connection or link identifier which was created by the previous call.



$link1 = mysql_connect("localhost", "user1", "secret");
$link2 = mysql_connect("localhost", "user1", "secret");
$link3 = mysql_connect("localhost", "user1", "secret");
//The three calls to mysql_connect above will return a link identifier to the same connection

$link4 = mysql_connect("localhost", "user2", "secret");
//A new connection will be returned since we have changed the username in the argume
In the above example, the second and third calls to mysql_connect will return the same connection which was created in the first call. No new connections will be established. This is as long as the same arguments are used in all the three calls. You can force the mysql_connect to create a new connection by setting the value of $newlink argument as TRUE.

Selecting Database

Now that we have a link identifier or connection to the mysql server, we need to “select” a database. A mysql server on a typical shared hosting server may have dozens or even hundreds of databases. So we need to select or specify a database against which we want to run our queries.



//Open a connection to the mysql server
$link = mysql_connect('localhost', 'user', 'secret');
if(!$link) {
 print('Failed to establish connection to mysql server!');
 exit();
}

//Select the database
$status = mysql_select_db('mydatabase');

Running Queries

We have connected to the database server and selected our database. Now we are ready to run queries using mysql_query function. See the example below:



//Open a connection to the mysql server
$link = mysql_connect("localhost", "user1", "secret");
if(!$link) {
 print("Failed to establish connection to mysql server!");
 exit();
}

//Select the database
$status = mysql_select_db("mydatabase");

//Run query
$query = "SELECT first_name,last_name FROM customers WHERE cust_id=23";
$rs = mysql_query($query);
if(!$rs) {
 print("Query Error: ".mysql_error());
}
$numrows = mysql_num_rows($rs);
print("Number of rows returned: $numrows");
mysql_query will return a result set on success and FALSE on error. This is true for “SELECT”, “SHOW”, “DESCRIBE”, and “EXPLAIN” queries. For other types of queries, it will return TRUE on success and FALSE on error.
Therefore in our example above, we will either get a result set or FALSE. Even if there is no customer with a cust_id of 23, we will still get a result set. You can check the number of rows returned by our query using mysql_num_rows function. Please note, mysql_num_rows is only meaningful for SELECT queries.

Using the result set

There are a number functions available which we can use to retrieve our values from the result set. If we know for sure that only a single row will be returned by the query, we can use the code below:



$query = "SELECT first_name,last_name FROM customers WHERE cust_id=23";
$rs = mysql_query($query);
if(!$rs) {
 print("Query Error: ".mysql_error());
}

//Number of rows reqturned by the query
$numrows = mysql_num_rows($rs);
print("Number of rows returned: $numrows");

//Fetch result set as an associative array
$customer = mysql_fetch_assoc($rs);
print($customer['first_name']);
print($customer['last_name']);
mysql_fetch_assoc returns an associative array. The column names correspond to the keys of this array and column values correspond to array values. In our example above, mysql_fetch_assoc will return an array similar to:



$customer['first_name'] = 'Jatinder';
$customer['last_name'] = 'Thind';
Other functions of interest while dealing with mysql databases are :
  1. mysql_unbuffered_query – This uses less memory than mysql_query. The downside is that you can not use mysql_num_rows if you use mysql_unbuffered_query
  2. mysql_real_escape_string – Escapes the special characters. Only available on PHP-4.3.0 and above
  3. addslashes – Similar to mysql_real_escape_string above. This is available in all PHP versions.
  4. mysql_error – Returns the error text from the previously called mysql function.

Submitting forms using PHP cURL

Posted by Muhammad Shiraz Kamboh 0 comments
In the previous article, we covered the PHP cURL basics. Specifically, we learned how to connect to a remote URL and retrieve the URL’s contents. In this article we will learn how to simulate form submission using PHP cURL.




To submit forms using cURL, we need to follow the below steps:
  1. Prepare the data to be posted
  2. Connect to the remote URL
  3. Post (submit) the data
  4. Fetch response and display it to the user
You may want to download the script used in this tutorial before starting.

Prepare data to be posted

Form data is essentially sent as name value pairs in the format “field1=field1_value&field2=field2_value&field3=field3_value”.
field1, field 2 etc. refer to the form fields and the field1_value, field2_value etc. refer to values of these fields. For our example we will assume that the data we want to post to the remote URL is contained in an associative array like so:
$data = array(); $data['first_name'] = 'Jatinder'; $data['last_name'] = 'Thind'; $data['password'] = 'secret'; $data['email'] = 'me@abc.com'; 
When a browser submits the form, it automatically urlencodes the data before sending it off. Similarly we will need to urlencode all data before posting it through cURL. You can find more about urlencode here.
 $post_str = ‘’; foreach($data as $key=>$val) { $post_str .= $key.’=’.urlencode($val).’&’; } $post_str = substr($post_str, 0, -1); 
The above code will leave us with string “first_name=Jatinder&last_name=Thind&password=secret&email=me%40abc.com” which can now be sent to the remote URL through cURL.

Connect to the remote URL

We have already covered this in the previous PHP cURL tutorial. Here is the code again in a nutshell.
 $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, ‘http://example.com/form-handler.php’ ); 

Post (submit) the form data

First we instruct cURL to a regular HTTP POST.
 curl_setopt($ch, CURLOPT_POST, TRUE); 
Next we tell cURL which data to send in the HTTP POST.
 curl_setopt($ch, CURLOPT_POSTFIELDS, $post_str); 

Execute request and fetch the response

 curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); $result = curl_exec($ch); curl_close($ch); echo $result; 
The above code snippet executes the cURL request, fetches the response of the form handler script and displays it to the user.
You can download the complete source code for the above PHP cURL tutorial here.

Simple PHP Login Member Area code and Tutorial

Posted by Muhammad Shiraz Kamboh Sunday, 25 March 2012 0 comments


(c) Balakrishnan 2009. All Rights Reserved
Usage: This script can be used FREE of charge for any commercial or personal projects. Enjoy!


Limitations:
- This script cannot be sold.
- This script should have copyright notice intact. Dont remove it please.
- This script may not be provided for download except from its original site.


System Requirements
Window Xp/ Window Vista
Winrar / Zip

 Size : 22 Kb

Popular Posts

About Me

My photo
I create this Blog for learn the all kind of tutorial about web developing | HTML, Java, PHP, Graphic designing, Corel Draw, Photoshop, Micromedia Flash, Swish and many more related software and internet programming tutorials.

Followers

Blog Archive