Sei sulla pagina 1di 55

Create user login in PHP Posted in PHP Tutorials | 131 Comments PHP is a good alternative when you decide

to add a password protected web pages on your web site. You can also use htaccess password protection but with PHP you can create a lot more complex and configurable protection. In this example I will use SESSION variables for login verification. Lets start with building a configuration file for setting up all the username/password combinations. Create a new passwords.php file and add the following code in it. 1 2 <?php 3 $USERS["username1"] = "password1"; $USERS["username2"] = "password2"; 4 $USERS["username3"] = "password3"; 5 6 function check_logged(){ global $_SESSION, $USERS; 7 if (!array_key_exists($_SESSION["logged"],$USERS)) { 8 header("Location: login.php"); 9 }; 10}; 11?> 12

Above code creates an $USER array with 3 username/password combinations. We also did a function which will be used later to check if an user is logged in or not. What we need now is a login page (called login.php) where users will enter their username and password and will login. 1 <?php 2 session_start(); 3 include("passwords.php"); { /// do after login form is submitted 4 if ($_POST["ac"]=="log") if ($USERS[$_POST["username"]]==$_POST["password"]) { /// check if 5 submitted 6 username and password exist in $USERS array 7 $_SESSION["logged"]=$_POST["username"]; } else { 8 echo 'Incorrect username/password. Please, try again.'; 9 }; 10}; 11if (array_key_exists($_SESSION["logged"],$USERS)) { //// check if user is 12logged or not echo "You are logged in."; //// if user is logged show a message 13 } else { //// if not logged show login form 14 echo '<form action="login.php" method="post"><input type="hidden" 15name="ac" value="log"> '; 16 echo 'Username: <input type="text" name="username" />'; echo 'Password: <input type="password" name="password" />'; 17 echo '<input type="submit" value="Login" />'; 18

19 20}; ?> 21

echo '</form>';

In order to use the user login feature for your PHP files you need to put that code at the very top of each of your PHP files that need to be protected. 1 <?php 2session_start(); /// initialize session 3include("passwords.php"); 4check_logged(); /// function checks if visitor is logged. 5If user is not logged the user is redirected to login.php page ?> 6 7your page code goes here 8

How to make a PHP calendar Posted in PHP Tutorials | 98 Comments

In this tutorial you will learn how to build your own web based calendar using PHP. This calendar is made from two parts. On top there are the links to the previous and the next month, and below them is the calendar itself. It will show the selected month name with the year following and the days of the month bellow in a table view. You will need a good PHP editor to help you with your development or if you are experienced enough you can use a plain text editing software such as Notepad. At the begining we have to decide how we are going to pass our parameters. We can use either

'hidden' input fields in out html code or pass them in the URL. In this tutorial we will use the second approach. We are going to need two parameters - one for the "month" and one for the "year". We will also need an array with month names: 1<?php = Array("January", "February", "March", "April", "May", "June", 2$monthNames "July", 3"August", "September", "October", "November", "December"); 4?> First we need to check if we have set up our parameters already. If we have not, we set them to the current month and year. (For detailed explanation of date() function please refer to PHP Manual ). 1<?php 2if (!isset($_REQUEST["month"])) $_REQUEST["month"] = date("n"); 3if (!isset($_REQUEST["year"])) $_REQUEST["year"] = date("Y"); 4?> Lets also set the variables that we are going to use in our calandar: 1 2 <?php 3 $cMonth = $_REQUEST["month"]; 4 $cYear = $_REQUEST["year"]; 5 6 $prev_year = $cYear; $next_year = $cYear; 7 $prev_month = $cMonth-1; 8 $next_month = $cMonth+1; 9 10if ($prev_month == 0 ) { $prev_month = 12; 11 $prev_year = $cYear - 1; 12 } 13if ($next_month == 13 ) { 14 $next_month = 1; $next_year = $cYear + 1; 15 16} 17?> 18 $cMonth and $cYear are used for the current month and year displayed on the calendar. For the "Previous" and "Next" links we will need the coresponding parameters. We set $prev_year and $next_year to the current one. Later we may have to change this but for now it is OK. We also have to set parameters for the next and previous months by adding and subtracting 1. Now is the catch. We have to check if our parameter has not gone over or down the limit. Since there are 12 months in a year if our parameter goes to 13 then it means that another year has passed by and we have to set our "month" parameter back to 1 ( January ) and add 1 to our "year" parameter. The other way around is when we go back in time and our "month" parameter goes to 0. Then we

have to decrease our "year" parameter by 1 and set the month paramether to 12 ( December ). Now as we set our links for previous and next months we turn to how to build the actual calendar. We create a table that will hold our calendar and add the links in one row. Then we add a table in a new row that will hold the days. We also include the month name and the year in the first on the new table. But because arrays are zero based, we need to subtract one from the "month" parameter value to get the correct name.
<table width="200"> <tr align="center"> <td bgcolor="#999999" style="color:#FFFFFF"> 1 <table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> 2 <td width="50%" align="left"> <a href="<?php echo $_SERVER["PHP_SELF"] . 3 "?month=". $prev_month . "&year=" . $prev_year; ?>" 4 style="color:#FFFFFF">Previous</a></td> 5 <td width="50%" align="right"><a href="<?php echo $_SERVER["PHP_SELF"] . 6 "?month=". $next_month . "&year=" . $next_year; ?>" style="color:#FFFFFF">Next</a> </td> 7 </tr> 8 </table> 9 </td> 10</tr> <tr> 11<td align="center"> 12<table width="100%" border="0" cellpadding="2" cellspacing="2"> 13<tr align="center"> 14<td colspan="7" bgcolor="#999999" style="color:#FFFFFF"><strong><?php echo 15$monthNames[$cMonth-1].' '.$cYear; ?></strong></td> </tr> 16<tr> 17<td align="center" bgcolor="#999999" 18style="color:#FFFFFF"><strong>S</strong></td> 19<td align="center" bgcolor="#999999" 20style="color:#FFFFFF"><strong>M</strong></td> <td align="center" bgcolor="#999999" 21style="color:#FFFFFF"><strong>T</strong></td> 22<td align="center" bgcolor="#999999" 23style="color:#FFFFFF"><strong>W</strong></td> 24<td align="center" bgcolor="#999999" style="color:#FFFFFF"><strong>T</strong></td> 25<td align="center" bgcolor="#999999" 26style="color:#FFFFFF"><strong>F</strong></td> <td align="center" bgcolor="#999999" style="color:#FFFFFF"><strong>S</strong></td> </tr>

Now we have to set the proper dates for our calendar. We have to make integer representation of the date so we can easily operate with it. Then we get the number of days of the selected month and the number representation (0 for Sunday through 6 for Saturday) of the first day of the month. All of these functions are fully explained in PHP Manual. Our loop that is going to print the dates starts at 0, because the days of the week start from 0 (Sunday). It has to loop through the number of days plus the offset of the first day of the month. We have to print new row for each week. We check this by modulus of the number of days in one week 7. If it equals 0 then it

is the begining of the week and we print open row tag <tr> and if it is the end of the week 6 we print close tag for this week </tr>. All we need to do is to check if the day that we print is before $startday. In this case we print empty tag. Otherwise we have to print the date. We make it by subtracting the $startday. we have to add one because we don't want our dates to start from 0. 1 <?php 2 $timestamp = mktime(0,0,0,$cMonth,1,$cYear); 3 $maxday = date("t",$timestamp); 4 $thismonth = getdate ($timestamp); 5 $startday = $thismonth['wday']; $i<($maxday+$startday); $i++) { 6 for ($i=0; if(($i % 7) == 0 ) echo "<tr>n"; 7 if($i < $startday) echo "<td></td>n"; 8 else echo "<td align='center' valign='middle' height='20px'>". ($i $startday + 1) . "</td>n"; 9 if(($i % 7) == 6 ) echo "</tr>n"; 10 } 11?> 12 Now we add just the finishing touches of the html and we have finished the calendar. 1</table> 2</td> 3</tr> 4</table>

PHP / MySQL select data and split on pages Posted in PHP Tutorials, MySQL Tutorials | 121 Comments This tutorial is going to show you how to SELECT data from a MySQL database, split it on multiple pages and display it using page numbers. We have MySQL table called students holding 90 records with the following fields: Name varchar(250) PhoneNumber varchar(250) Instead of doing a single SELECT query and display all the 90 records on a single page we can have 5 pages each containing maximum 20 records. To do this we will need to use the LIMIT clause for SELECT command so we can limit the query to show only 20 records. The LIMIT clause also allows you to specify which record to start from. For example this query 1$sql = "SELECT * FROM students ORDER BY name ASC LIMIT 0, 20";

returns 20 records sorted by name starting from the first record. This next query 1$sql = "SELECT * FROM students ORDER BY name ASC LIMIT 50, 20";

shows 20 records sorted again by name but this time it will start from the 50th record. So basically in this clause (LIMIT start, count) start specify the starting record and count specifies how many records to show. Next thing to do is to make a PHP file called pagination.php which will show the first 20 records from our table. The code below selects and then prints the data in a table. 1 2 <?php 3 if (isset($_GET["page"])) { $page = $_GET["page"]; } else { $page=1; }; 4 $start_from = ($page-1) * 20; 5 $sql = "SELECT * FROM students ORDER BY name ASC LIMIT $start_from, 20"; 6 $rs_result = mysql_query ($sql, $connection); 7 ?> 8 <table> <tr><td>Name</td><td>Phone</td></tr> 9 <?php 10while ($row = mysql_fetch_assoc($rs_result)) { 11?> <tr> 12 <td><? echo $row["Name"]; ?></td> 13 <td><? echo $row["PhoneNumber"]; ?></td> 14 </tr> 15<?php 16}; 17?> </table> 18 19

Now, when you open pagination.php in your web browser you will see table showing the first 20 records from your students table. The first 2 lines of the above code 1if (isset($_GET["page"])) { $page = $_GET["page"]; } else { $page=1; }; 2$start_from = ($page-1) * 20;

are used to create a $start_from variable depending on the page that we want to view. Later you will see that we will pass a page value using the URL (e.g. pagination.php?page=2) to go to different pages. Next we need to find out the total amount of records in our table and the number of pages that we will need. To do this we run another query using COUNT() function. 1$sql = "SELECT COUNT(Name) FROM students"; 2$rs_result = mysql_query($sql,$connection); 3$row = mysql_fetch_row($rs_result); 4$total_records = $row[0];

The $total_records is now equal to the number of records that we have in our database, in our case 90. We have 20 records per page so the total number of pages that will be needed is 5 (4 pages with 20 records and last page will have 10 records). Calculating the amount of pages needed using PHP can be done using ceil() function. 1$total_pages = ceil($total_records / 20);

We divide the total number of records by records per page and then the ceil() function will round up the result. Now we have 2 new variables - $total_records equal to 90 and $total_pages equal to 5. To print page numbers and associate URLs to each number we will use for() cycle. 1<?php 2for ($i=1; $i<=$total_pages; $i++) { echo "<a href='pagination.php?page=".$i."'>".$i."</a> "; 3 }; 4 5?>

Above code will print numbers from 1 to 5 and for each number will create different link. pagination.php?page=1 pagination.php?page=2 pagination.php?page=3 pagination.php?page=4 pagination.php?page=5 as you can see each link passes different page value which is used in the SELECT query above. At the end you should have a file like this (remember to add the MySQL connection string): 1 <?php 2 if (isset($_GET["page"])) { $page = $_GET["page"]; } else { $page=1; }; = ($page-1) * 20; 3 $start_from $sql = "SELECT * FROM students ORDER BY name ASC LIMIT $start_from, 20"; 4 $rs_result = mysql_query ($sql,$connection); 5 ?> 6 <table> 7 <tr><td>Name</td><td>Phone</td></tr> <?php 8 while ($row = mysql_fetch_assoc($rs_result)) { 9 ?> <tr> 10 <td><? echo $row["Name"]; ?></td> 11 <td><? echo $row["PhoneNumber"]; ?></td> 12 </tr> 13<?php 14};

15?> 16</table> <?php 17$sql = "SELECT COUNT(Name) FROM students"; 18$rs_result = mysql_query($sql,$connection); 19$row = mysql_fetch_row($rs_result); 20$total_records = $row[0]; 21$total_pages = ceil($total_records / 20); 22for ($i=1; $i<=$total_pages; $i++) { 23 echo "<a href='pagination.php?page=".$i."'>".$i."</a> "; 24}; 25?> 26 27 28 29 30

This pagination.php file will print a table with maximum 20 records per page and at the bottom 5 page numbers each pointing to a page showing different 20 records. Do not forget that for a small fee I can add pagination to all your PHP files. Let me know if you need help with this and I will give you a quote.

PHP validation and verification Posted in PHP Tutorials | 47 Comments Today we are going to review a very important part of the development process of a web application. The validation of users input. This is one the trickiest parts of any application at all. Why is that? Because the developer doesn't control it. You can write the best algorithm in the world, but still if it includes user input there is a place for mistakes. Even if we put some coplicated logic to prevent the input of wrong symbols, check the consistence of the data and do whatever possible to make sure that it is all OK, there is still possibility that the users enter the wrong number. Though all said, we must try to prevent the most of human errors and the best way to do this is by using Regular Expressions. Basicly Regular Expressions are used for string matches. They are based on search and pattern matching strings in text. A lot of books are written about them, there are even some programming languages designed especially for Regular Expressions. But today we are just going to take a brief look at how regular expressions can help us with user input. First of all I suggest that you get familiar with some basic concepts of the language. It's syntax is fully explained in PHP Manual --> Pattern Syntax. Now let's get to work. I'll present some of the most common problems with user input. I'm pretty sure that you met most of them if not all. We are going to create a registration form with required input fields. They are as follows:

- Full Name - Address - Passport - Email - Phone - Zip code - Date - Username - Password Here is the test form that we will use PHP validation example (download here http://static.phpjabbers.com/files/tutorials/verification.zip) We have to define some variables that will hold our error messages. Their values have to be cleared every time we reload our page. 1 2$errName = ""; $errAddress = ""; 3$errEmail = ""; 4$errPassport = ""; 5$errPhone = ""; 6$errZip = ""; = ""; 7$errDate $errUser = ""; 8$errPass = ""; 9

There are two ways to use regular expressions in php. One is the true PHP style in which case we have to use ereg() function and the other is to use Perl style syntax for our validations. In this case we have to use preg_match() function. In this tutorial we will use preg_match() because it is faster in most cases and also supports the most common regular expression syntax. It also gives us more capabilities, that we can use. We will start with validation of the name of the user. We will allow only letters, space and a dash. So we create our regexp (Regular Expression). We will make a class for our possible values. The class is created when we enclose some symbols in parences. This is our class: [a-zA-Z -] Our class includes all letters between a-z (all lower case letters), A-Z (all upper case letters), space and a dash. Now we have to set this class to apply for every character that we enter. So we add a (+) plus sign after our class definition. We are still missing something. We have not defined the range of our validation test. We have to set which part of the text we are validating. If we don't do this our regular expression will be satisfied if it finds even one match in the characters that we enter, which is of no use for us. How do we do this? We put our string between /^$/ start and end characters. "^" means the start of the line and "$" means the end of it. We are ready to build our regexp.

/^[a-zA-Z -]+$/ The forward slash is used by preg_match to define the start and the end of our regexp. Now we are finished, are we? There is just one more thing to do. The way that we defined our class allows the user to enter dash at the begining of the name. This is something we want to prevent. So we have to add something to our regexp, so it will disallow this. [A-Z] We define a new class for the first letter of the user name. It can contain only upper case letters. Now we combine what we have done so far, to get the final result. The return of preg_match() is 0 if there isn't a match. In that case we have to set our error variable, so we can show some meaningful message to the user. /^[A-Z][a-zA-Z -]+$/ 1with upper case letter. 2if(preg_match("/^[A-Z][a-zA-Z -]+$/", $_POST["name"]) === 0) 3$errName = '<p class="errText">Name must be from letters, dashes, spaces and
must not start with dash</p>'; // Full Name must contain letters, dashes and spaces only and must start

Let's move forward to the next valitaion field, which is going to be the address. Not much to do here, because it can contain a lot of symbols. We just have to define one class that hold them all. /^[a-zA-Z0-9 _-.,:"']+$/ We translate this regexp as: From the begining to the end of the address string check if our character is one of the following a-z, A-Z, 0-9, space, underscore, dash, dot, comma, semicolons, double and sigle quotes. You can add any character that you think may be part of an address. The thing to notice here is that when we have quotes we have to put an escape character before them. 1// Address must be word characters only if(preg_match("/^[a-zA-Z0-9 _-.,:"']+$/", $_POST["address"]) === 0) 2$errAddress = '<p class="errText">Address must be only letters, numbers or 3one of the following _ - . , : " '</p>';

Our next task is to create a regexp for email validation. Here we are going to include another future of the expressions which is constans that represend predefined classes. Here is a list of those that we will use: w = [0-9A-Za-z_] Class includes digits, letters and underscore character. d = [0-9] Class includes only digits These constants save a lot of typing and make source code easier to read and understand. What is the mask for an email? The first part the username can contain letters, digits, dots and underscore

character. It has to begin with letter and if we have dot it must be followed by letter. Then it must be followed by @ sign and again the first part. At the end we must have a dot followed by 2 to 4 letters. Whenever we have a character that has special meaning in regexp and we want to use it as character, we have to escape it with backslash. 1if(preg_match("/^[a-zA-Z]w+(.w+)*@w+(.[0-9a-zA-Z]+)*.[a-zA-Z]{2,4}$/", 2$_POST["email"]) === 0) 3$errEmail = '<p class="errText">Email must comply with this mask:
chars(.chars)@chars(.chars).chars(2-4)</p>'; // Email mask

The next string for validation is passport. It can contain only numbers and be 10 or 12 digits. But how we set how many characters we want. We put the desired number of characteras in parences {} and our regexps will look like this /^d{10}$/ and /^d{12}$/. How we combine these two expressions so that we use either one or the other. We use OR. It's sign is "|". Our statement is complete /^d{10}$|^d{12}$/. 1// Passport must be only digits 2if(preg_match("/^d{10}$|^d{12}$/", $_POST["passport"]) === 0) 3$errPassport = '<p class="errText">Passport must be 10 or 12 digits</p>';

I will present a phone mask. It can be a lot different, but it is simle enough to be easily customized. You just have to define the number of diggits in every part of the phone number and choose a delimiter. It can be any symbol you want. Zip code is also very easy to implement.
1-800-999-9999 1// Phone mask 2if(preg_match("/^d{1}-d{3}-d{3}-d{4}$/", $_POST["phone"]) === 0) = '<p class="errText">Phone must comply with this mask: 1-333-3333$errPhone 4444</p>'; 4// Zip must be 4 digits 5if(preg_match("/^d{4}$/", $_POST["zip"]) === 0) 6$errZip = '<p class="errText">Zip must be 4 digits</p>';

Now we will make date mask. It will look like this: YYYY-MM-DD. Our date will be made only by diggits. You already now how to set the lenght of the year, but the month and day can be between 1 and 2 diggits in lenght. We set this by separating the two values by comma {1,2}. This means that all the numbers in this interval are valid value. 1// Date mask YYYY-MM-DD if(preg_match("/^[0-9]{4}-[0-9]{1,2}-[0-9]{1,2}$/", $_POST["date"]) === 0) 2$errDate = '<p class="errText">Date must comply with this mask: YYYY-MM3DD</p>';

The last thing to check in our registration - validation form is for username and password of our user. Username can be any string that consist of letters, diggits and uderscore character ( "w" predefined class). We want the username to be at least 5 chars long. This is accomplised by this

statement {5,}. The missing value after the comma means that it can be of any value equal or bigger that 5. 1// User must be digits and letters if(preg_match("/^[0-9a-zA-Z_]{5,}$/", $_POST["user"]) === 0) 2$errUser = '<p class="errText">User must be bigger that 5 chars and contain 3only digits, letters and underscore</p>';

A good password is the hardest thing to check for. To pass a validation test it must contain at least one lower case letter, one upper case letter and one digit. This will make it hard to break. A thing to know before we start - the dot represents any character. For our purpose we have to make some groups that represent the password. They are defined using the parences (). Each group will check for a particular condition. The first one will check the lenght of our string. It must be equal or bigger than 8. ?= is called a possitive lookahead. A positive lookahead says "the next text must be like this and follow these rules." So when we take the "next text" it must be of the type ".{8,}". We declare our first regexp condition as (?=.{8,}). It states that our string must be equal or bigger that 8 and can contain any character. The second rule that we want to apply to the password is to contain at least one diggit. Again we take our string and check it against our condition (?=.*[0-9]). Similarly we do the other conditions. One is for lowercase letters and the other is for uppercase letter (?=.*[a-z]) (?=.*[A-Z]). This is the minimal requirements for our password. The user may want even stronger password. So we add ".*" at the begining and at the end of the password. This means that any number from 0 to more can be inserted.
// Password must be strong 1if(preg_match("/^.*(?=.{8,})(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z]).*$/", === 0) 2$_POST["pass"]) $errPass = '<p class="errText">Password must be at least 8 characters and 3must contain at least one lower case letter, one upper case letter and one 4digit</p>'; }

This concludes our tutorial. You see what a powerfull tool regular experessions are and how they can help us in form input verifications. They are way more complex than what you see here, but knowing at least the basics is essential. So get those heavy books and start reading. I hope that those examples help you with your work.

Make contact form and send email in PHP Posted in PHP Tutorials | 308 Comments Having a contact form on your web site is vital when you need to know what your site visitors think about your web site. We will first create a simple contact form with 3 fields - Email address, Name, Comments. I will use a table to align the 3 fields and the Send button. Create a new file and paste the code below in it. Save it

as test.php and upload it to your web server. Now, you have a web page (http://www.yourdomain.com/test.php) with a simple contact form on it. 1 2 <form action="test.php" method="post"> 3 <table width="400" border="0" cellspacing="2" cellpadding="0"> <tr> 4 <td width="29%" class="bodytext">Your name:</td> 5 <td width="71%"><input name="name" type="text" id="name" size="32"></td> 6 </tr> 7 <tr> <td class="bodytext">Email address:</td> 8 <td><input name="email" type="text" id="email" size="32"></td> 9 </tr> 10<tr> 11<td class="bodytext">Comment:</td> 12<td><textarea name="comment" cols="45" rows="6" id="comment" class="bodytext"></textarea></td> 13</tr> 14<tr> 15<td class="bodytext"> </td> 16<td align="left" valign="top"><input type="submit" name="Submit" 17value="Send"></td> </tr> 18</table> 19</form> 20

Then we will need the actual PHP code which will send the email when the above form is submitted. We will need to define the email that the message should be sent to ($ToEmail) and also the subject for the message that will be sent ($EmailSubject). Change youremail@site.com to your email address where the message should be sent and also add an appropriate subject for you message. The $mailheader variable is used to define the email message header. We set the From, Reply-To and Content-type fields for the message. There are some more fields that can be used but for this example we will only use these 3. Depending on your server configuration you may need to have the From and Reply-to fields be a valid email address from your server.If you have a domain name mysite.com, then you should use a valid email address such as contact@mysite.com. In this example I am sending the email using the actual email address that is submitted via the form on site. Next all the data submitted via the web form is taken from the $_POST variable and saved in the $MESSAGE_BODY variable. Using the nl2br function you will make all the new lines in your comments box appear as new lines in your email message too. Having all the needed data for our email message we will use the mail() function which will send that email for us. 1 2 3 4 5 6
<?php $ToEmail = 'youremail@site.com'; $EmailSubject = 'Site contact form'; $mailheader = "From: ".$_POST["email"]."\r\n"; $mailheader .= "Reply-To: ".$_POST["email"]."\r\n"; $mailheader .= "Content-type: text/html; charset=iso-8859-1\r\n"; $MESSAGE_BODY = "Name: ".$_POST["name"]."";

7 $MESSAGE_BODY .= "Email: ".$_POST["email"].""; 8 $MESSAGE_BODY .= "Comment: ".nl2br($_POST["comment"]).""; mail($ToEmail, $EmailSubject, $MESSAGE_BODY, $mailheader) or die 9 ("Failure"); 10?> 11

All we have to do now is to combine the web form and email sending code into a single page. We will use an IF statement to check if the form has been submitted and if so it will send that email and will show a "Your message was sent" message on the screen instead of the web form. 1 2 <?php if ($_POST["email"]<>'') { 3 $ToEmail = 'youremail@site.com'; 4 $EmailSubject = 'Site contact form'; $mailheader = "From: ".$_POST["email"]."\r\n"; 5 $mailheader .= "Reply-To: ".$_POST["email"]."\r\n"; 6 $mailheader .= "Content-type: text/html; charset=iso-8859-1\r\n"; 7 $MESSAGE_BODY = "Name: ".$_POST["name"].""; 8 $MESSAGE_BODY .= "Email: ".$_POST["email"].""; $MESSAGE_BODY .= "Comment: ".nl2br($_POST["comment"]).""; 9 mail($ToEmail, $EmailSubject, $MESSAGE_BODY, $mailheader) or die 10 ("Failure"); 11 ?> 12Your message was sent 13<?php 14} else { 15?> <form action="test.php" method="post"> 16<table width="400" border="0" cellspacing="2" cellpadding="0"> 17<tr> 18<td width="29%" class="bodytext">Your name:</td> 19<td width="71%"><input name="name" type="text" id="name" size="32"></td> 20</tr> <tr> 21<td class="bodytext">Email address:</td> 22<td><input name="email" type="text" id="email" size="32"></td> 23</tr> 24<tr> class="bodytext">Comment:</td> 25<td <td><textarea name="comment" cols="45" rows="6" id="comment" 26class="bodytext"></textarea></td> 27</tr> 28<tr> 29<td class="bodytext"> </td> <td align="left" valign="top"><input type="submit" name="Submit" 30value="Send"></td> 31</tr> 32</table> 33</form> 34<?php }; 35?> 36

37 38 39

Date and time formatting with PHP Posted in PHP Tutorials | 5 Comments Hello again. Today's tutorial is separated into two parts. In the first part we will get familiar with date and time formatting and in the second we will exercise date and time manipulations. Probably most of you are familiar with formatting, but for those who are not and for those that would like to remind of it please read below. You may think that date and time topic is not very important in web applications and you'll be wrong. Almost every one has it. It may be not so obvious, it may be even hidden from the regular users, but it is there. Just think about it for a second. Where do we always use date and time? ... If you still haven't got the answer here it is. The most common place for dates and time are databases and log files. Why? We all want to have a log of users' actions. We log everything so we can keep track of what happens, because one day it will inevitably go wrong and we would like to now what caused the problem. The main part of every log is "when it happened". It may be only the administrator of the web application, who is reading it, or it can be hundreds of company's employees that carefully sort every event that took part, but they all need to know "date & time". You may still ask yourself why I started with User Interface but take a look at this: 1202395558 Not many people can read this clearly without any problems. This is the current server time. Now see this: 2008-02-07 16:45:58 Feb 07 08 4:45:58 pm For those of you that are not genius enjoying themselves by calculating big integer time, I will reveal the mystery of how we can format dates and time. We will begin with dates formatting. It is done using date() function. It accepts two parameters. Format string and time as integer. We will use time() for current time integer. Let's see some examples. 1echo date("d-m-y", time());
// 07-02-08

The dash between the characters in the format string above is exactly what the output is going to be separated with. 1echo date("D j/n/Y", time());
// Thu 7/2/2008

The dash here is replaced with forward slash. 1echo date("jS of F Y", time());
// 7th of February 2008

We can use any character we want here, just keep in mind that if it has a special meaning it has to be escaped. And just to be sure that there are no mistakes I suggest that you always escape every character you use. 1echo date("d M y", time());
//07 Feb 08

Formatting the date using short representation for month names and short year. 1echo date("l jS of F", time());
// Thursday 7th of February

Full day and month name with ordinal suffix for the day of the month. Date format characters' legend by examples: d - Numeric representation of a day, with leading zeros 01 through 31. m - Numeric representation of a month, with leading zeros 01 through 12. y - Numeric representation of a year, two digits. D - Textual representation of a day, three letters Mon through Sun. j - Numeric representation of a day, without leading zeros 1 through 31. n - Numeric representation of a month, without leading zeros 1 through 12. Y - Numeric representation of a year, four digits. S - English ordinal suffix for the day of the month. Consist of 2 characters st, nd, rd or th. F - Textual representation of a month, January through December. M - Textual representation of a month, three letters Jan through Dec. l textual representation of the day of the week Sunday through Saturday. Now we move on to our next task which is time formatting. We are still going to use the same date() function, but with different format characters. 1echo date("G:i:s", time());
//16:45:58

Working with time is a little bit simpler, because there is only one way to represent minutes and seconds.

1echo date("H:i:s", time());

//16:45:58

Despite of the very few options for minutes and seconds formats we have a lot of hour formatting styles. This one represents hours with leading zeroes 0 through 23. 1echo date("g:i a.", time());
//4:45 pm.

This is an example of time format with lowercase ante meridiem and post meridiem (am/pm). 1echo date("h:i A.", time());
//04:45 PM.

This is an example of time format with uppercase AM/PM. Time format characters' legend by examples: G 24-hour format of an hour without leading zeros 0 through 23. i Numeric representation of minutes with leading zeros 00 through 59. s Numeric representation of seconds with leading zeros 00 through 59. H 24-hour format of an hour with leading zeros 00 through 23. a Lowercase Ante meridiem and Post meridiem am or pm. g 12-hour format of an hour without leading zeros 1 through 12. A Uppercase Ante meridiem and Post meridiem AM or PM. h 12-hour format of an hour with leading zeros 01 through 12. And when we combine both date and time formatting we get some really nice looking output strings. 1PM.
echo date("l jS of F g:i A.", time()); // Thursday 7th of February 4:45

1echo date("D M j G:i:s T Y", time());

// Thu Feb 7 16:45:58 EET 2008

Now take a deep breath, get some chips and get ready because we are headed for the second part of our tutorial which is date time manipulations.

Reading files with PHP Posted in PHP Tutorials | 2 Comments Today we will start a series of tutorials about file manipulations. The series will include file reading and writing. Then we will see how to copy, move or delete a file. We will also go throught directory creation and listing. Latter we will review change of user/group rights of both files and folders and renaming. Of course our tutorial will include a lot of

examples, that most of the time make reading the text around them needless. Today's tutorial is about file reading and writing. It is separated in two parts named suprisingly File Reading and File Writing. First of all you must make sure that you have permissions. This is a complex subject that includes FileSystem permissions, PHP restrictions and also Apache HTTP server configuration. For the purpose of our tutorial I assume that you have them set. Let's go then. The starting point of every file operation is getting a file handle that will point to our file. This is done by using fopen() function. 1<?php 2// Open Unix file 3$handle = fopen("/home/phpjabbers/somefile.txt", "r"); // Open Windows file. Mind that you have to escape the backslashes or I 4advise you to use forward slashes. 5$handle = fopen("c:\data\info.txt", "rt"); 6$handle = fopen("c:/data/info.txt", "rt"); 7?>

There are several ways to open the file, they are called modes, and it all depends on what you want to do with it. If you just want to deal with already existing file and you do not want to delete it's content you have to use the following two modes: r - opens the file for reading only and places the cursor at the beginning of the file. r+ - opens the file for reading and writing and places the cursor at the beginning of the file. If you want to create a new file or replace the existing one you have to use one of the following two modes: w - opens the file for writing only and places the cursor at the beginning of the file. If the file exists it empties it's contents (truncates the file to zero length). It the file does not exist, it makes an attempt to create it. w+ - the same as above only that this time the file is open for reading also. Another two writing modes allow us different approach: a - opens the file for writing only and places the cursor at the end of it. If the file does not exist, attempt to create it. a+ - opens the file for reading and writing and places the cursor at the end of it. If the file does not exist, attempt to create it. The last two modes are used when we want to create a file. x - create a file and open it for writing only. This mode places the file pointer at the beginning of the file. An important notice about this mode is that, if the file already exists, the function will fail and will return FALSE.

x+ - the same as above but create and open the file for reading also. IMPORTANT: When working with files on Windows based operating systam there are two more modes that you must know. They are combined with the other file open parameters. t - is used when you are working with text files. What is does is translate your line ending characters (n to rn). b - this mode must be used when working with non-text files. It is strongly recommended that you use b flag when opening files on Windows. If you don't you might experience strange problems with your file. Now that we have our file we can start working with it. PART 1 - FILE READING ( examples included ) First we will focus on reading files. There are several way to do it. We will start with reading text files. Most of the time we need to read our file line by line. For this operation we use this function - file(); It reads the entire file into array. file() - Reads text file into an array. 1 <?php 2// file example 3$lines = file("/tmp/files/InputTextFile.txt"); 4foreach ($lines as $line_num => $line) { echo "Line #{$line_num} : " . $line . "n"; 5 } 6?> 7

As you can see it is very simple to output text file content. What more can we add here. Just that file() supports a few optional parameters: FILE_USE_INCLUDE_PATH - Search for the file in the include_path. FILE_IGNORE_NEW_LINES - Do not add newline at the end of each array element(in our case $line). FILE_SKIP_EMPTY_LINES - Skip empty lines. A similar function that reads the entire content of a file, but this time to a string is file_get_contents(). It supports two additional parameters, which sometimes can be very helpfull: offset and maxlen bytes (they were added in PHP 5.1). Offset specifies where to start reading from, and maxlen specifies how many bytes to read from the source. This function is bynary safe. file_get_contents() - Reads entire file into a string. It also shows how to read 1KB starting at the 128th byte.

1<?php 2// file_get_contents example 3$file = file_get_contents("/tmp/files/InputTextFile.txt",0,null,128,1024); 4echo $file; 5?>

Here is another example this time reading remote file. 1<?php 2// file_get_contents example $file = 3file_get_contents("http://www.example.com/tmp/files/InputTextFile.txt"); 4echo $file; 5?>

More direct way to print the file to the buffer is readfile() function. What is does is just that. You do not even have to echo it. It returns the bytes that have been read. readfile - Outputs the entire file to the output buffer 1<?php 2// readfile() example 3$file = "/tmp/files/InputTextFile.txt"; 4$bytesRead = readfile($file); 5echo $bytesRead; ?> 6

The next function that can help us reading a file is fgets(). It reads a line starting from the file pointer position and returns it as a string. You can also specify the lenght of bytes you want it to read. If you tend to use it, have in mind, that reading file ends when length - 1 bytes have been read, a newline is reached, or EOF is reached (whichever comes first). This function requires file handle to operate with. In our example we read our file in 8KB chunks at most. fgets() - Gets a line from file pointer 1 <?php 2 // fgets example // Windows OS 3 $file = "c:/tmp/files/InputTextFile.txt"; 4 $handle = fopen($file, "rt"); 5 if ($handle) { while (!feof($handle)) { 6 $buffer = fgets($handle, 8192); 7 echo $buffer; 8 } 9 fclose($handle); 10}

11?> 12 13

The last function that we will take a look at and show an example of it is fread(). It is used to read binary files. It takes a file handle and reads length bytes from the file pointer. Reading file ends when length bytes or 8192 bytes (8KB) have been read, end of file (EOF) is reached or when a packet becomes available (for network streams), whichever comes first. fread() - Binary-safe file read 1 <?php 2// fread example 3$file = "/tmp/files/picture.gif"; 4// REMEMBER: If this is Windows OS you have to use "rb" 5$handle = fopen($file, "r"); 6$contents = fread($handle, filesize($file)); fclose($handle); 7?> 8

This example shows how you can read binary files from the web. 1 <?php 2$handle = fopen("http://www.example.com/picture.gif", "r"); 3$contents = ''; 4while (!feof($handle)) { $contents = $contents . fread($handle, 8192); 5 } 6 fclose($handle); 7?> 8

It is not much of a use to print the contents of a binary file, but it you want to write it to a new file this function is the way to do it.

Make php counter Posted in PHP Tutorials | 9 Comments It is always good to know how many visits a web page has. Most of the hosting companies offer great tools for monitoring your web site visitors behaviour but often

you just need to see how many times a web page has been visited. Using PHP and a plain text file this has never been easier. The example below uses a flat-text database so no MySQL database is needed. I am currently working on a more advanced counter script which gives a lot more details about each visits and I will post it on site when it is done. First, lets make a new php page and also a count.txt file with just 0 digit in it. Upload the count.txt file on your web server. Depending on server configuration you may need to change the permission for this file to 777 so it is writeable by the counter script that we are going to use. Now, lets do the actual PHP code. 1 <?php 2$count = file_get_contents("count.txt"); 3$count = trim($count); 4$count = $count + 1; 5$fl = fopen("count.txt","w+"); 6fwrite($fl,$count); fclose($fl); 7?> 8

First line opens the count.txt file and reads the current counter value. Then the trim() function is used to remove any new line characters so we have an integer. On the next line we increment the current counter value by one and then using the fopen, fwrite and fclose commands we write the new value to our count.txt file. Please, note that this counter is not suitable for web pages that have many visitors. A large number of file read/writes may corrupt the counter value. For high traffic web sites you should consider using a MySQL based web counter script.

Date and time manipulations with PHP Posted in PHP Tutorials | 3 Comments One day you may need to find out what day of the week is going to be 27th of November 2037. Well, 27th of November is probably not the day you are wondering about, and in most cases you will change that date with your birthday, but still the question is the same. What I can do is to tell you how to check the day of your birthday say 30 or 50 or 100 years from now. I will also tell you how to manipulate dates and time and this is what the second part of this tutorial will show. The thing to begin with is how to construct a random date. You have to use this function mktime(). Let's say you are born on 14th of May 1983. We create this date as follows. 1<?php 2echo date("jS of M Y", mktime(0, 0, 0, 5, 14, 1983)); 3?>
// 14th of May 1983

Maybe you know, maybe you don't, but you were born on Saturday which is the 1 day of the

year and is in 19 week. Now let's see which day of the week is going to be this date, but next year. 1<?php 2echo date("D j m Y", mktime(0, 0, 0, 5, 14, 2009)); 3?>
// Thu 14 05 2009

The same way that we extracted the current year with date() function, we can extract all other elements that represent date time. Knowing this will let us easily operate with time. Suppose you want to find out the number of days between two dates. Let's say 2nd february 2008 and your next birthday. 1<?php echo date("j", (mktime(0, 0, 0, 5, 14, $nextYear) - mktime(0, 0, 0, 2, 7, 22008))); // 8 3?>

So the way to calculate time is by creating appropriate mktime() function. To find out how much time you have between 2 given "times", your code should look similar to this: 1<?php echo date("g:i a.", (mktime(15, 30, 0, 1, 1, 2007) - mktime(11, 45, 0, 1, 1, 22007))); //5:45 am. 3?>

mktime() function is very helpfull doing date arithmetic, because it will automatically calculate the correct value for out-of-range input. Here are some examples: 1echo date("F j 2echo date("F j 3echo date("F j 42007 1:00 am. 5echo date("F j 2007 1:01 am. 6?>
<?php Y", mktime(0, 0, 0, 1, 32, 2007)); //February 1 2007 Y", mktime(0, 0, 0, 13, 1, 2007)); // January 1 2008 Y g:i a.", mktime(25, 0, 0, 1, 1, 2007)); // January 2 Y g:i a.", mktime(0, 61, 0, 1, 1, 2007)); // January 1

You have probably noticed how easy we can calculate dates. 1 2 3 4 5 6


<?php //How to get the day 3 days from now: $today = date("j"); $thisMonth = date("n"); $thisYear = date("Y"); echo date("F j Y", mktime(0,0,0, $thisMonth, $today+3, $thisYear));

7 //1 week from now: 8 list($today,$thisMonth,$thisYear) = explode(" ", date("j n Y")); echo date("F j Y", mktime(0,0,0, $thisMonth, $today+7, $thisYear)); 9 10//4 months from now: 11list($today,$thisMonth,$thisYear) = explode(" ", date("j n Y")); 12echo date("F j Y", mktime(0,0,0, $thisMonth+4, $today, $thisYear)); 13 14//3 years, 2 months and 35 days from now: 15list($today,$thisMonth,$thisYear) = explode(" ", date("j n Y")); echo date("F j Y", mktime(0,0,0, $thisMonth+2, $today+35, $thisYear+3)); 16?> 17 18 19

This concludes today's tutorial. This was a little bit longer than the usual ones but it's because the two parts are tightly coupled and we can't separate them from one another. I hope you enjoyed our time again.

Connect to MySQL database Define few variables with your MySQL database connection settings and connect to MySQL database using mysql_connect() and mysql_select_db() functions. 1 2 <?php 3 4 // set your MySQL login details $db_host = "localhost"; 5 $db_user = "username"; 6 $db_pass = "password"; 7 $db_name = "databasename"; 8 9 $connection = mysql_connect($db_host,$db_user,$db_pass); { 10if (!(mysql_select_db($db_name,$connection))) echo "Could not connect to the database"; 11 } 12?> 13 Convert URL in text Parse text and convert all URLs and emails in clickable links function convertLinks($text) 1 { 2 $text = preg_replace('/(((f|ht){1}tps?:\/\/)[-a-zA-Z039@:;%_\+.~#?&\/\/=]+)/', '<a href="\\1" target="_blank">\\1</a>', $text);

$text = preg_replace('/([[:space:]()[{}])(www.[-a-zA-Z04 9@:;%_\+.~#?&\/\/=]+)/', '\\1<a href="http://\\2" target="_blank">\\2</a>', 5 $text); 6 $text = preg_replace('/(([0-9a-zA-Z\.\-\_]+)@([0-9a-zA-Z\.\7\_]+)\.([0-9a-zA-Z\.\-\_]+))/', '<a href="mailto:$1">$1</a>', $text); return $text; }

Count lines in a file Open a text file and count how many lines of text it has. 1<?php 2$file = "somefile.txt"; 3 4$lines = count(file($file)); 5 6echo "There are $lines lines in $file"; 7?>

Database connection using PDO 1 2 // you can choose from MySQL and SQLite 3 define('DB_DRIVER', 'mysql'); 4 // SQLite don't use host parameter 5 define('DB_HOST', 'localhost'); 'login'); 6 define('DB_USER', define('DB_PASS', 'password'); 7 // In case of SQLite usage, change it to path/to/your.db, for example 8 define('DB_NAME', 'testdb'); 9 10function initDB(){ // Switch correct pattern for chosen DBMS. 11 // You can add your own patterns for PostgreSQL or MS SQL, for example 12 if(DB_DRIVER=='mysql') 13 $pattern = '%1$s:host=%2$s;dbname=%3$s'; elseif(DB_DRIVER=='sqlite') 14 $pattern = '%1$s:%3$s'; 15 else 16 die("Can't create DB instance! Reason: Unsuported DB driver"); 17 18 // Construct correct data source name for chosen database type 19 $dsn = sprintf($pattern, DB_DRIVER, DB_HOST, DB_NAME); 20 try{ 21 $pdoInst = new PDO($dsn, DB_USER, DB_PASS); 22 $pdoInst->setAttribute(PDO::ATTR_ERRMODE, 23 PDO::ERRMODE_EXCEPTION);
<?php

24 25 26 27 28 29 30 31} 32?> 33 34 35 36 37 38 39 40

}catch(PDOException $e){ // Stop script and throw message if error occurred die($e->getMessage()); } // Let us know that all is ok. Only for debug. echo 'PDO Instance created!'; return $pdoInst;

Draw a table using PHP Create HTML table using PHP using two for loops - one for the rows and one for the columns 1 2 <?php 3 $rows = 10; // define number of rows 4 $cols = 4;// define number of columns 5 echo "<table border='1'>"; 6 7 for($tr=1;$tr<=$rows;$tr++){ 8 9 echo "<tr>"; for($td=1;$td<=$cols;$td++){ 10 echo "<td>row: ".$tr." column: ".$td."</td>"; 11 } 12 echo "</tr>"; 13} 14 15echo "</table>"; 16?> 17

Get file extension pass filename in the $str variable and function will return file extension only. 1function getFileExtension($str)

2{ 3 4 5 6} 7

$arrSegments = explode('.', $str); // may contain multiple dots $strExtension = $arrSegments[count($arrSegments) - 1]; $strExtension = strtolower($strExtension); return $strExtension;

Save text in a file Create a PHP variable and write its value into a file 1 2 <?php 3 $save_text = "text data text data"; 4 5 // create filename.txt file 6 $fp = fopen("filename.txt", "w"); 7 8 // Write the text stired in $save_text variable 9 fwrite($fp, $save_text); 10 Close the file 11// fclose($fp); 12 13?> 14

url encode / decode by vir0e5


description
Url Encode is a technique employed in order to convert a string used in a URL into a valid URL forma and decode url
<?php //*************************************************************************** ************* //Created by vir0e5 //My blog --> http://vir0e5.blogspot.com //Forum --> http://indonesian-cyber.org //Greetz --> Allah S.W.T , Mohammad S.A.W //All Crew : indonesiancoder,indonesianhacker, devilzc0de, tecon, phl //*************************************************************************** *************

echo"<title>URL Encode / Decode</title>"; echo"<div align=center>URL Encode / Decode"; $bandit= stripslashes($_POST['c0de']); if ($bandit == "") { $bandit = $_GET['c0de']; } $action = $_POST['action']; if ($action == "") { $action = $_GET['action']; if ($action == "encode"){ $action = "enc0de"; } elseif ($action == "decode") { $action = "dec0de"; } } switch($action){ case "enc0de": $output = urlencode ($bandit); if(!$output){ echo 'Ada yang salah!!!'; } echo"<center><table width='380'><td>"; echo"<br><center>&#34;urlencode() function&#34;</center><hr></br>"; echo "<p> Input : " . $bandit . "</p>"; echo "<p> Output: " . $output ."</p>"; echo "<p><a href='javascript:history.back(0);'> << Back </a></p>"; break; case "dec0de": $output = urldecode($bandit); if(!$output){ echo 'Ada yang salah!!!'; exit; } echo"<center><table width='380'><td>"; echo"<br><center>&#34;urldecode() function&#34;</center><hr></br>"; echo "<p> Input : " . $bandit . "</p>"; echo "<p> Output : " . $output ."</p>"; echo "<p><a href='javascript:history.back(0);'> << Back </a></p>"; break; default: echo"<p>Input your text on text area...and enjoy it!!</p>"; echo '<form id="form1" name="form1" method="post" action="?encode/vir0e5\deco de"> <p> <textarea name="c0de" id="c0de" rows=8 cols=40 ></textarea> </p>

<p>Pilih yang mau di cari</p> <p><input type=radio name="action" id="action" value="enc0de">Encod e</p> <p><input type=radio name="action" id="action" value="dec0de">Decod e</p> <input type="submit" class = "button" name="submit" id="submit" onCli ck=" if(c0de.value==\'\'){alert(\'mana teksnya kang???\'); return false;}" value="Submit" /> <input type="reset" name="reset" class="button" value="Reset"/> </p> </form>'; break; } ?>

time ago by admin


description
Displays how long ago something happened, such as when something was posted. "1 day ago", "2 months ago", etc.
<?php function prettyDate($date){ $time = strtotime($date); $now = time(); $ago = $now - $time; if($ago < 60){ $when = round($ago); $s = ($when == 1)?"second":"seconds"; return "$when $s ago"; }elseif($ago < 3600){ $when = round($ago / 60); $m = ($when == 1)?"minute":"minutes"; return "$when $m ago"; }elseif($ago >= 3600 && $ago < 86400){ $when = round($ago / 60 / 60); $h = ($when == 1)?"hour":"hours"; return "$when $h ago"; }elseif($ago >= 86400 && $ago < 2629743.83){ $when = round($ago / 60 / 60 / 24); $d = ($when == 1)?"day":"days"; return "$when $d ago";

}elseif($ago >= 2629743.83 && $ago < 31556926){ $when = round($ago / 60 / 60 / 24 / 30.4375); $m = ($when == 1)?"month":"months"; return "$when $m ago"; }else{ $when = round($ago / 60 / 60 / 24 / 365); $y = ($when == 1)?"year":"years"; return "$when $y ago"; } } echo echo echo echo prettyDate("2012-07-22 prettyDate("2010-11-12 prettyDate("2012-01-01 prettyDate("2001-05-30 12:23:45")."<br 22:25:45")."<br 01:00:00")."<br 00:00:00")."<br />"; />"; />"; />";

Version: 1 Type: Full Script Category: Databases License: GNU General Public License Description: Generates a MySQL query from all fields on an HTML page. To add a new colum to insert data into, simply add a new field (make sure the field name is the same as teh column name in the MySQL table) and it does it all for you. I wrote this when I got tired of INSERT into whatever (id, name, date)VALUES('', '', '') and decided I wanted something to just generate it for me.

1 2 3 4 5 6 7 8 9 10 11 12

<?php //Keith Thibodeaux //qalimas [at) gmail (doT] com /* Note that to add a new column to the query, just add in an input box to the HTML, the PHP generates an insert for each field. This simply displays the query to be executed, to make it execute and not display, change the link "echo "The MySQL Statement..." to "$this>exec($query);" at the bottom of the create_new function. You would also have to uncomment the MySQL function and set it up accordingly. */

13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58

//MySQL Class class MySQL { /* function MySQL() { if (!$dblink = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD)) { die (mysql_errno() . ": " . mysql_error()); } if (!mysql_select_db(DB_DATABASE)) { die (mysql_errno() . ": " . mysql_error()); } } */ static function exec($query) { if (!$result = mysql_query($query)) { die (mysql_errno() . ": " . mysql_error()); } return $result; }

function create_new($table, $data) { $query = "INSERT INTO $table ("; foreach ($data as $field => $value) { $query .= "$field,"; } $query .= ") VALUES ("; foreach ($data as $field => $value) { $query .= "'$value',"; } $query .= ")rplme"; $query = str_replace(",) VALUES (", ") VALUES (", $query); $query = str_replace(",)rplme", ")", $query); echo "The MySQL Statement that would be executed is <b>$query</b>"; } } //End MySQL Class $mysql = new MySQL; if ($_GET['action'] == "do") { $data = array();

59 foreach ($_POST as $field => $value) { 60 if ($field != "submit" && $field != "whatever field name you dont 61 want to include (add to the query)") { 62 $data[$field] = $value; 63 } } 64 65 $mysql->create_new("customer", $data); 66 67 68 } else { 69 //Begin else content 70 ?> 71 <form action="?action=do" method="POST"> <table> 72 73 <tr> 74 75 <td>First Name</td> 76 77 <td align="right"><input size="25" type="text" 78 name="csfname" /></td> 79 80 </tr> 81 <tr> 82 83 <td>Last Name</td> 84 85 <td align="right"><input size="25" type="text" 86 name="cslname" /></td> 87 88 </tr> 89 <tr> 90 91 <td>Email Address</td> 92 93 <td align="right"><input size="25" type="text" 94 name="csemail" /></td> 95 96 </tr> 97 98 <tr> 99 <td>Home Phone</td> 100 101 <td align="right"><input size="25" type="text" 102 maxlength="13" name="csphome" /></td> 103 104 </tr>

105 <tr> 106 107 <td>Cell Phone</td> 108 109 <td align="right"><input size="25" type="text" 110maxlength="13" name="cspcell" /></td> 111 112 </tr> 113 <tr> 114 115 <td>Fax Number</td> 116 117 <td align="right"><input size="25" type="text" 118maxlength="13" name="cspfax" /></td> 119 120 </tr> 121 122 <tr> 123 <td>Street Address (123 Fake st)</td> 124 125 <td align="right"><input size="25" type="text" 126 name="csstadd" /></td> 127 128 </tr> 129 130 <tr> 131 <td>City (Lake Charles)</td> 132 133 <td align="right"><input size="25" type="text" 134 name="cscity" /></td> 135 136 </tr> 137 138 <tr> 139 140 <td>State (Abbreviation)</td> 141 <td align="right"><input size="25" type="text" 142 143maxlength="2" name="csstate" /></td> 144 </tr> 145 146 <tr> 147 148 <td>Zip Code (5 Digits)</td> 149 150 <td align="right"><input size="25" type="text"
maxlength="5" name="cszip" /></td>

151 </tr> 152 153 </table> 154 155 <br /> 156 157 <div style="text-align: right;"><input class="button" 158type="submit" value="Create" name="submit" /></div> 159</form> 160<?php else content 161//end } 162 163?> 164 165 166 167 168 169 170 171

Tutorials\ PHP

\Rating:

1 2 3

4 5

User Membership With PHP


Tom Cameron on Nov 10th 2008 with 371 Comments Tutorial Details

Technology: PHP, CSS Difficulty: Intermediate Completion Time: 1-2 hours

View post on Tuts+ BetaTuts+ Beta is an optimized, mobile-friendly and easy-to-read version of the Tuts+ network.

A tutorial for the very beginners! No matter where you go on the internet, theres a staple that you find almost everywhere user registration. Whether you need your users to register for security or just for an added feature, there is no reason not to do it with this simple tutorial. In this tutorial we will go over the basics of user management, ending up with a simple Member Area that you can implement on your own website.

Introduction
In this tutorial we are going to go through each step of making a user management system, along with an inter-user private messaging system. We are going to do this using PHP, with a MySQL database for storing all of the user information. This tutorial is aimed at absolute beginners to PHP, so no prior knowledge at all is required in fact, you may get a little bored if you are an experienced PHP user! This tutorial is intended as a basic introduction to Sessions, and to using Databases in PHP. Although the end result of this tutorial may not immediately seem useful to you, the skills that you gain from this tutorial will allow you to go on to produce a membership system of your own; suiting your own needs. Before you begin this tutorial, make sure you have on hand the following information:

Database Hostname this is the server that your database is hosted on, in most situations this will simply be localhost.

Database Name, Database Username, Database Password before starting this tutorial you should create a MySQL database if you have the ability, or have on hand the information for connecting to an existing database. This information is needed throughout the tutorial.

If you dont have this information then your hosting provider should be able to provide this to you. Now that weve got the formalitiies out of the way, lets get started on the tutorial!

Step 1 - Initial Configuration


Setting up the database

As stated in the Introduction, you need a database to continue past this point in the tutorial. To begin with we are going to make a table in this database to store our user information. The table that we need will store our user information; for our purposes we will use a simple table, but it would be easy to store more information in extra columns if that is what you need. In our system we need the following four columns:

UserID (Primary Key) Username Password EmailAddress

In database terms, a Primary Key is the field which uniquely identifies the row. In this case, UserID will be our Primary Key. As we want this to increment each time a user registers, we will use the special MySQL option auto_increment. The SQL query to create our table is included below, and will usually be run in the SQL tab of phpMyAdmin.
view plaincopy to clipboardprint? 1. 2. 3. 4. 5. 6. CREATE TABLE `users` ( `UserID` INT(25) NOT NULL AUTO_INCREMENT PRIMARY KEY , `Username` VARCHAR(65) NOT NULL , `Password` VARCHAR(32) NOT NULL , `EmailAddress` VARCHAR(255) NOT NULL );

Creating a base file

In order to simplify the creation of our project, we are going to make a base file that we can include in each of the files we create. This file will contain the database connection information, along with certain configuration variables that will help us out along the way. Start by creating a new file: base.php, and enter in it the following code:
view plaincopy to clipboardprint? 1. 2. 3. 4. 5. 6. <?php session_start();

$dbhost = "localhost"; // this will ususally be 'localhost', but can sometimes differ $dbname = "database"; // the name of the database that you are going to use for this project $dbuser = "username"; // the username that you created, or were given, to access your databas e 7. $dbpass = "password"; // the password that you created, or were given, to access your database 8. 9. mysql_connect($dbhost, $dbuser, $dbpass) or die("MySQL Error: " . mysql_error()); 10. mysql_select_db($dbname) or die("MySQL Error: " . mysql_error()); 11. ?>

Lets take a look at a few of those lines shall we? Theres a few functions here that weve used and not yet explained, so lets have a look through them quickly and make sense of them if you already understand the basics of PHP, you may want to skip past this explanation.
1. session_start();

This function starts a session for the new user, and later on in this tutorial we will store information in this session to allow us to recognise users who have already logged in. If a session

has already been created, this function will recognise that and carry that session over to the next page.
view plaincopy to clipboardprint? 1. mysql_connect($dbhost, $dbuser, $dbpass) or die("MySQL Error: " . mysql_error()); 2. mysql_select_db($dbname) or die("MySQL Error: " . mysql_error());

Each of these functions performs a separate, but linked task. The mysql_connect function connects our script to the database server using the information we gave it above, and the mysql_select_db function then chooses which database to use with the script. If either of the functions fails to complete, the die function will automatically step in and stop the script from processing leaving any users with the message that there was a MySQL Error.

Step 2 - Back to the Frontend


What do we need to do first?

The most important item on our page is the first line of PHP; this line will include the file that we created above (base.php), and will essentially allow us to access anything from that file in our current file. We will do this with the following line of of PHP code. Create a file named index.php, and place this code at the top.
view plaincopy to clipboardprint? 1. <?php include "base.php"; ?> Begin the HTML page

The first thing that we are going to do for our frontend is to create a page where users can enter their details to login, or if they are already logged in a page where they can choose what they then wish to do. In this tutorial I am presuming that users have basic knowledge of how HTML/CSS works, and therefore am not going to explain this code in detail; at the moment these elements will be unstyled, but we will be able to change this later when we create our CSS stylesheet. Using the file that we have just created (index.php), enter the following HTML code below the line of PHP that we have already created.
view plaincopy to clipboardprint? 1. <!DOCTYPE html PUBLIC "//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

2. 3. 4. 5. 6. 7. 8. 9.

<html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>User Management System (Tom Cameron for NetTuts)</title> <link rel="stylesheet" href="style.css" type="text/css" /> </head> <body> <div id="main">

What shall we show them?

Before we output the rest of the page we have a few questions to ask ourselves:
1. Is the user already logged in? o Yes we need to show them a page with options for them to choose. o No we continue onto the next question. 2. Has the user already submitted their login details? o Yes we need to check their details, and if correct we will log them into the site. o No we continue onto the next question. 3. If both of the above were answered No, we can now assume that we need to display a login form to the user.

These questions are in fact, the same questions that we are going to implement into our PHP code. We are going to do this in the form of if statements. Without entering anything into any of your new files, lets take a look at the logic that we are going to use first.
view plaincopy to clipboardprint? 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. <?php if(!empty($_SESSION['LoggedIn']) && !empty($_SESSION['Username'])) { // let the user access the main page } elseif(!empty($_POST['username']) && !empty($_POST['password'])) { // let the user login } else { // display the login form } <?>

Looks confusing, doesnt it? Lets split it down into smaller sections and go over them one at a time.
view plaincopy to clipboardprint?

1. if(!empty($_SESSION['LoggedIn']) && !empty($_SESSION['Username'])) 2. { 3. // let the user access the main page 4. }

When a user logs into our website, we are going to store their information in a session at any point after this we can access that information in a special global PHP array $_SESSION. We are using the empty function to check if the variable is empty, with the operator ! in front of it. Therefore we are saying: If the variable $_SESSION['LoggedIn'] is not empty and $_SESSION['Username'] is not empty, execute this piece of code. The next line works in the same fashion, only this time using the $_POST global array. This array contains any data that was sent from the login form that we will create later in this tutorial. The final line will only execute if neither of the previous statements are met; in this case we will display to the user a login form. So, now that we understand the logic, lets get some content in between those sections. In your index.php file, enter the following below what you already have.
view plaincopy to clipboardprint? 1. <?php 2. if(!empty($_SESSION['LoggedIn']) && !empty($_SESSION['Username'])) 3. { 4. ?> 5. 6. <h1>Member Area</h1> 7. <pThanks for logging in! You are <b><?=$_SESSION['Username']?></b> and your email addres s is <b><?=$_SESSION['EmailAddress']?></b>.</p> 8. 9. <?php 10. } 11. elseif(!empty($_POST['username']) && !empty($_POST['password'])) 12. { 13. $username = mysql_real_escape_string($_POST['username']); 14. $password = md5(mysql_real_escape_string($_POST['password'])); 15. 16. $checklogin = mysql_query("SELECT * FROM users WHERE Username = '".$username."' AND P assword = '".$password."'"); 17. 18. if(mysql_num_rows($checklogin) == 1) 19. { 20. $row = mysql_fetch_array($checklogin); 21. $email = $row['EmailAddress']; 22.

23. 24. 25. 26. 27. 28. 29. 30. 31. 32. 33. 34. 35. 36. 37. 38. 39. 40. 41. 42. 43. 44. 45. 46. 47. 48. 49. 50. 51. 52. 53. 54. 55. 56. 57. 58. 59.

$_SESSION['Username'] = $username; $_SESSION['EmailAddress'] = $email; $_SESSION['LoggedIn'] = 1; echo "<h1>Success</h1>"; echo "<p>We are now redirecting you to the member area.</p>"; echo "<meta http-equiv='refresh' content='=2;index.php' />"; } else { echo "<h1>Error</h1>"; echo "<p>Sorry, your account could not be found. Please <a href=\"index.php\">click here t o try again</a>.</p>"; } } else { ?> <h1>Member Login</h1> <p>Thanks for visiting! Please either login below, or <a href="register.php">click here to regist er</a>.</p> <form method="post" action="index.php" name="loginform" id="loginform"> <fieldset> <label for="username">Username:</label><input type="text" name="username" id="usern ame" /><br /> <label for="password">Password:</label><input type="password" name="password" id="p assword" /><br /> <input type="submit" name="login" id="login" value="Login" /> </fieldset> </form> <?php } ?> </div> </body> </html>

Hopefully, the first and last code blocks wont confuse you too much. What we really need to get stuck into now is what youve all come to this tutorial for the PHP code. Were now going to through the second section one line at a time, and Ill explain what each bit of code here is intended for.
view plaincopy to clipboardprint?

1. $username = mysql_real_escape_string($_POST['username']); 2. $password = md5(mysql_real_escape_string($_POST['password']));

There are two functions that need explaining for this. Firstly, mysql_real_escape_string a very useful function to clean database input. It isnt a failsafe measure, but this will keep out the majority of the malicious hackers out there by stripping unwanted parts of whatever has been put into our login form. Secondly, md5. It would be impossible to go into detail here, but this function simply encrypts whatever is passed to it in this case the users password to prevent prying eyes from reading it.
view plaincopy to clipboardprint? 1. $checklogin = mysql_query("SELECT * FROM users WHERE Username = '".$username."' AND Pas sword = '".$password."'"); 2. 3. if(mysql_num_rows($checklogin) == 1) 4. { 5. $row = mysql_fetch_array($checklogin); 6. $email = $row['EmailAddress']; 7. 8. $_SESSION['Username'] = $username; 9. $_SESSION['EmailAddress'] = $email; 10. $_SESSION['LoggedIn'] = 1;

Here we have the core of our login code; firstly, we run a query on our database. In this query we are searching for everything relating to a member, whose username and password match the values of our $username and $password that the user has provided. On the next line we have an if statement, in which we are checking how many results we have received if there arent any results, this section wont be processed. But if there is a result, we know that the user does exist, and so we are going to log them in. The next two lines are to obtain the users email address. We already have this information from the query that we have already run, so we can easily access this information. First, we get an array of the data that has been retrieved from the database in this case we are using the PHP function mysql_fetch_array. I have then assigned the value of the EmailAddress field to a variable for us to use later. Now we set the session. We are storing the users username and email address in the session, along with a special value for us to know that they have been logged in using this form. After this is all said and done, they will then be redirect to the Member Area using the META REFRESH in the code. So, what does our project currently look like to a user?

Great! Its time to move on now, to making sure that people can actually get into your site.
Let the people signup

Its all well and good having a login form on your site, but now we need to let users be able to use it we need to make a login form. Make a file called register.php and put the following code into it.
view plaincopy to clipboardprint? 1. <?php include "base.php"; ?> 2. <!DOCTYPE html PUBLIC "//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 3. <html xmlns="http://www.w3.org/1999/xhtml"> 4. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 5. 6. <title>User Management System (Tom Cameron for NetTuts)</title> 7. <link rel="stylesheet" href="style.css" type="text/css" /> 8. </head> 9. <body> 10. <div id="main"> 11. <?php 12. if(!empty($_POST['username']) && !empty($_POST['password'])) 13. { 14. $username = mysql_real_escape_string($_POST['username']); 15. $password = md5(mysql_real_escape_string($_POST['password'])); 16. $email = mysql_real_escape_string($_POST['email']); 17.

18. ); 19. 20. 21. 22. 23. 24. 25. 26. 27. 28. 29. 30. 31. 32. 33. 34. 35. 36. 37. 38. 39. 40. 41. 42. 43. 44. 45. 46. 47. 48. 49. 50. 51. 52.

$checkusername = mysql_query("SELECT * FROM users WHERE Username = '".$username."'"

if(mysql_num_rows($checkusername) == 1) { echo "<h1>Error</h1>"; echo "<p>Sorry, that username is taken. Please go back and try again.</p>"; } else { $registerquery = mysql_query("INSERT INTO users (Username, Password, EmailAddress) VA LUES('".$username."', '".$password."', '".$email."')"); if($registerquery) { echo "<h1>Success</h1>"; echo "<p>Your account was successfully created. Please <a href=\"index.php\">click here to login</a>.</p>"; } else { echo "<h1>Error</h1>"; echo "<p>Sorry, your registration failed. Please go back and try again.</p>"; } } } else { ?> <h1>Register</h1> <p>Please enter your details below to register.</p> <form method="post" action="register.php" name="registerform" id="registerform"> <fieldset> <label for="username">Username:</label><input type="text" name="username" id="usern ame" /><br /> <label for="password">Password:</label><input type="password" name="password" id="p assword" /><br /> <label for="email">Email Address:</label><input type="text" name="email" id="email" />< br /> <input type="submit" name="register" id="register" value="Register" /> </fieldset> </form>

53. 54. 55. 56. 57. <?php 58. } 59. ?>

60. 61. </div> 62. </body> 63. </html>

So, theres not much new PHP that we havent yet learnt in that section. Lets just take a quick look at that SQL query though, and see if we can figure out what its doing.
view plaincopy to clipboardprint? 1. $registerquery = mysql_query("INSERT INTO users (Username, Password, EmailAddress) VALUES ('".$username."', '".$password."', '".$email."')");

So, here we are adding the user to our database. This time, instead of retrieving data were inserting it; so were specifying first what columns we are entering data into (dont forget, our UserID will go up automatically). In the VALUES() area, were telling it what to put in each column; in this case our variables that came from the users input. So, lets give it a try; once youve made an account on your brand-new registration form, heres what youll see for the Members Area.

Make sure that they can logout

Were almost at the end of this section, but theres one more thing we need before were done here a way for users to logout of their accounts. This is very easy to do (fortunately for us); create a new filed named logout.php and enter the following into it.
view plaincopy to clipboardprint? 1. <?php include "base.php; $_SESSION = array(); session_destroy(); ?> 2. <meta http-equiv="refresh" content="0;index.php">

In this we are first resetting our the global $_SESSION array, and then we are destroying the session entirely. And thats the end of that section, and the end of the PHP code. Lets now move onto our final section.

Step 3 - Get Styled


Im not going to explain much in this section if you dont understand HTML/CSS I would highly reccomend when of the many excellent tutorials on this website to get you started. Create a new file named style.css and enter the following into it; this will style all of the pages that we have created so far.
view plaincopy to clipboardprint? 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. 22. 23. 24. 25. 26. 27. 28. 29. *{ margin: 0; padding: 0; } body { font-family: Trebuchet MS; } a{ color: #000; } a:hover, a:active, a:visited { text-decoration: none; } #main { width: 780px; margin: 0 auto; margin-top: 50px; padding: 10px; border: 1px solid #CCC; background-color: #EEE; } form fieldset { border: 0; } form fieldset p br { clear: left; } label { margin-top: 5px; display: block; width: 100px; padding: 0; float: left;

30. 31. 32. 33. 34. 35. 36. 37. 38. 39. 40. 41.

} input { font-family: Trebuchet MS; border: 1px solid #CCC; margin-bottom: 5px; background-color: #FFF; padding: 2px; } input:hover { border: 1px solid #222; background-color: #EEE; }

Now lets take a look at a few screenshots of what our final project should look like:

The login form.

The member area.

The registration form.


And finally

And thats it! You now have a members area that you can use on your site. I can see a lot of people shaking their heads and shouting at their monitors that that is no use to them youre right. But what I hope any beginners to PHP have learned is the basics of how to use a database, and how to use sessions to store information. The vital skills to creating any web application.

SQL Injection

Published in PHP Architect on 15 Apr 2004 Last Updated 15 Apr 2004 42 comments

Thanks to Alyona Lompar, this article is also available in Ukrainian. Welcome to another edition of Security Corner. This month's topic is SQL injection, an attack vector that frequents the minds of PHP developers, but for which there is a shortage of good documentation. Most web applications interact with a database, and the data stored therein frequently originates from remote sources. Thus, when creating an SQL statement, you often use input in its construction. A typical SQL injection attack exploits this scenario by attempting to send fragments of valid SQL queries as unexpected values of GET and POST data. This is why an

SQL injection vulnerability is often the fault of poor filtering and escaping, and this fact cannot be stressed enough. This article explains SQL injection by looking at a few example attacks and then introducing some simple and effective safeguards. By applying best practices, you can practically eliminate SQL injection from your list of security concerns.

SQL Injection
For a moment, place yourself in the role of an attacker. Your goal is initially simple. You want to get any unexpected SQL statement executed by the database. You're only looking to get something to work, because that will reveal the fact that the application has a potential vulnerability. You have as many chances as you want, and you have a lot of information to work with. For example, consider the simple authentication form shown in Figure 1. Figure 1:

In order to get more information about this form, you view the source: Toggle Code View 1. 2. 3. 4. 5.
<form action="/login.php" method="POST"> <p>Username: <input type="text" name="username" /></p> <p>Password: <input type="text" name="password" /></p> <p><input type="submit" value="Log In" /></p> </form>

You can already make a very educated guess about the type of SQL statement that this application might use to verify the access credentials. It will most likely be a SELECT statement.

You can also make a guess about the naming convention used in the database table, because it probably matches the simple names used in the HTML form. (It's also possible that you can cause an error that reveals this information to you.) Because this form is for authentication, there is probably WHERE clause that uses $_POST['username'] and $_POST['password']. From all of this, you might predict the following: Toggle Code View 1. 2. 3. 4. 5. 6. 7. 8.
<?php $sql = "SELECT count(*) FROM users WHERE username = '{$_POST['username']}' AND password = '...'"; ?>

Assuming this guess is correct, what can you do to manipulate this query? Imagine sending the following username: Toggle Code View 1. chris' /* The SQL statement becomes the following: Toggle Code View 1. 2. 3. 4.
SELECT count(*) FROM users WHERE username = 'chris' /*' AND password = '...'";

In this example, /* is used to begin a multi-line comment, effectively terminating the query at that point. This has been tested successfully with MySQL. A standard comment in SQL begins with --, and it's trivial to try both. This query suggests a successful authentication attempt as long as the chris account exists, regardless of the password. This particular attack is frequently used to steal accounts. Of course, any username can be used (admin is a popular target). Thus, by sending a malformed username, you can manage to log in without having a valid account. Keep in mind that creativity plays a large role in most attacks. In the previous example, the attack is limited by the type of query (SELECT) and in the way the username and password are used. In other words, as an attacker, you are somewhat bound, and your attacks must try to

exploit the situation within these bounds. Other types of queries present new opportunities, and the best practices mentioned in this article apply to all SQL injection attacks.

WHERE Hacking
The WHERE clause is used to restrict the records that a particular query matches. For a SELECT statement, it determines the records that are returned. For an UPDATE statement, it determines the records that are modified. For a DELETE statement, it determines the records that are deleted. If a user can manipulate the WHERE clause, there are many opportunities to make drastic changes selecting, updating, and deleting arbitrary records in the database. Imagine a SELECT statement intended to fetch all credit card numbers for the current user: Toggle Code View 1. 2. 3. 4. 5. 6. 7.
<?php $sql = "SELECT card_num, card_name, card_expiry FROM credit_cards WHERE username = '{$_GET['username']}'"; ?>

In this particular case, the application might not even solicit the username but instead provide it in a link: Toggle Code View 1. <a href="/account.php?username=shiflett"> 2. Credit Card Information 3. </a> If a user can have multiple cards, the application might loop through the results of a database query, displaying the card number, name on the card, and expiration date for each card. Imagine a user who visits the following resource: Toggle Code View 1. /account.php?username=shiflett%27+OR+username+%3D+%27lerdorf This submits the following value for the username: Toggle Code View

1. shiflett' OR username = 'lerdorf If used in the previous SQL query, $sql has the following value: Toggle Code View 1. SELECT card_num, card_name, card_expiry 2. FROM credit_cards 3. WHERE username = 'shiflett' OR username = 'lerdorf' Now the user sees a list of all credit cards belonging to either shiflett or lerdorf. This is a pretty major security vulnerability. Of course, a larger vulnerability exists in this particular example, because a user can arbitrarily pass any username in the URL. In addition, a username that causes the WHERE clause to match all records can potentially expose all records: Toggle Code View 1. shiflett' OR username = username Imagine if this particular username is stored in the database (using a separate SQL injection attack) as the attacker's own username. Every query that is restricted by a WHERE clause in order to only apply the user's own record can potentially apply to all records instead. This is not only extremely dangerous, but it also makes further attacks very convenient.

Input Filtering
This article assumes magic_quotes_gpc is disabled. If it is enabled, you can disable it or use the fix_magic_quotes() function to repair the input. There are best practices that you should follow to prevent SQL injection attacks, and these offer a very high level of protection. The most important step is to filter all input (data that comes from a remote source). This includes $_GET, $_POST, $_COOKIE, etc. To help clarify this, consider the following HTML form: Toggle Code View 1. 2. 3. 4. 5. 6. 7. 8.
<form action="/receive.php" method="POST"> <select name="color"> <option value="red">red</option> <option value="green">green</option> <option value="blue">blue</option> </select> <input type="submit"> </form>

Clearly, the expected values are red, green, and blue. So, the input filtering should verify this: Toggle Code View 1. <?php 2. 3. $clean = array(); 4. 5. switch ($_POST['color']) { 6. case 'red': 7. case 'green': 8. case 'blue': 9. $clean['color'] = $_POST['color']; 10. break; 11. default: 12. /* Error */ 13. break; 14. } 15. 16. ?> This code uses a separate array ($clean) to store the filtered data. It is a good idea to choose a naming convention that will help you identify potentially tainted data. In this example, $clean['color'] can be trusted to contain a valid color, because it is first initialized and then only assigned the value of $_POST['color'] if that value passes the test. The two most important points for input filtering are:

Only accept valid data rather than trying to prevent invalid data. Choose a naming convention that helps you distinguish tainted data from filtered data.

Escaping Output
With properly filtered input, you're already pretty well protected against malicious attacks. The only remaining step is to escape it such that the format of the input doesn't accidentally interfere with the format of the SQL statement. If you are using MySQL, this simply requires you to pass all data through mysql_real_escape_string() prior to use: Toggle Code View 1. <?php 2. 3. $mysql = array(); 4. 5. $mysql['color'] = mysql_real_escape_string($clean['color']);

6. 7. $sql = "SELECT username 8. FROM users 9. WHERE favorite_color = '{$mysql['color']}'"; 10. 11. ?> In this case, assuming $clean['color'] is created by the previous example, you can be sure that the color only contains alphabetic characters. (It's one of red, green, or blue.) Thus, the escaping might seem superfluous, and it is. However, it is still a good habit to always escape data. This practice will help you avoid forgetting this crucial step, and it adheres to the principle of defense in depth, which stresses the importance of redundant safeguards.

PHP how to calculate age from date of birth


/ Published in: PHP

URL: http://www.barattalo.it/2010/02/10/php-how-to-calculate-age-from-date-of-birth/ Expand | Embed | Plain Text


1. // input $date string format: YYYY-MM-DD 2. function age($date){ 3. list($year,$month,$day) = explode("-",$date); 4. $year_diff = date("Y") - $year; 5. $month_diff = date("m") - $month; 6. $day_diff = date("d") - $day; 7. if ($day_diff < 0 || $month_diff < 0) $year_diff--; 8. return $year_diff; 9. }

Find duplicate records


/ Published in: MySQL

Expand | Embed | Plain Text


1. SELECT id, COUNT(*) as n 2. FROM my_table

3. GROUP BY id 4. HAVING n >1;

PHP User authentification


/ Published in: PHP

user authentification Expand | Embed | Plain Text


1. <?php 2. if (!isset($_SERVER['PHP_AUTH_USER']) || !($_SERVER['PHP_AUTH_USER'] == 'xxx' && $_SERVER['PHP_AUTH_PW'] == 'xxx')) { 3. header('WWW-Authenticate: Basic realm="DBU Manager"'); 4. header('HTTP/1.0 401 Unauthorized'); 5. echo 'Access denied'; 6. exit(); 7. } 8. ?>

Potrebbero piacerti anche