Introduction
Occasionally a site administrator will want to make certain material available online, but also have it accessible to only a select few. Some examples of this might be student records, personalized information, email and even personal photo albums.
Of course there are many ways to restrict access to information ranging from web server configurations to third party programs. In this tutorial, we'll take a look at the basic theory behind a user authentication system using PHP.
Storing Passwords
Before we can begin coding with PHP, we need to first take a brief look at passwords. There are many different ways to manage and store a user's login ID and passwords, but one common method is to store them in a database.
For security purposes, the passwords themselves should not be stored in the database in a plain text manner. Instead, the password can be processed by a one-way, irreversible encryption or hashing function and then the jumbled result is what is actually stored. That means the password supplied later will need to be encrypted/hashed before we compare it with the stored value. If they both match then we know the password is good.
PHP's sha1 function should suffice for our purposes. It accepts a string and returns a 40 character hexadecimal hash representation. This hash cannot be converted back to the original string. The following is an example of sha1 in action:
We'll assume for this tutorial that a database table named Users exists which stores the username and passwords hashed with the sha1 function.
It's common mistake to not make the password column large enough to store the entire hash. Using sha1, the column should be 40 characters.
Getting the User Login
An HTML form is used to obtain the user's login credentials. The form displays 2 input fields--one to obtain the login ID and another to obtain the password.
The userid input field accepts the user's login id while the password field will accept the user's password. The password field might show asterisks or dots as the value is entered, but remember that the form will send it's data in clear text. A secure connection should be made using HTTPS. For more information on that subject see my tutorial Generating Your Own Security Certificates For Use With Apache/HTTPS.
The form here submits its information to a script named validate.php as specified by the form's action attribute. It's that script that will be responsible for checking the user's login ID and password in the database and allowing the user to continue.
Processing the Login
The actual authentication can take place once we have the user's login ID and password. We need to encrypt or hash the password the same way it was initially done.
With the ID and password value, we can query the database for any matching records. The following SQL statement is designed to return records where the login ID and password hash match.
SELECT * FROM Users WHERE User = '$user' AND Password = '$pass'
If the query returns a record set then the login credentials are valid and the user may have access to the protected information. If the query fails to return a record then the credentials are invalid and access is denied.
The validate.php script that would accomplish all of that might resemble the following:
Instead of simply echoing "Access Granted" or "Access Denied" as shown here, your script can set cookies or start sessions, redirect the user to the login form or perform whatever else is needed.
Persisting the Authentication
Once access to a resource has been granted to a user, it's typical for the access privileges to persist for a period of time. PHP sessions offer a nice way to carry information such as authentication throughout a series of pages. This way, a user won't have to provide a user ID and password each time a resource is accessed.
The validate.php script would initiate a session, set an access token and then redirect the user to the secured document.
After which each secured resource would continue the session and check for the access token.
I recommend Hermawan Haryanto's tutorial Using Sessions in PHP for more information on working with PHP sessions.
Conclusion
Authentication allows various resources to be published on the Internet but viewable only by those who can present the appropriate credentials. With the information presented in this tutorial you should be able to construct your own authentication system.
You might even want to organize your code in a set of functions or a class; the code can be written to be rather self-sufficient and then inserted in the top of each resource with include or require.
About The Author
Timothy Boronczyk lives in Syracuse, NY, where he works as an E-Services Coordinator for a local credit union. He has a background in elementary education, over 5 years experience in web design and has written tutorials on web design, PHP, Ruby, XML and various other topics. His hobbies include photography and composing music.
Occasionally a site administrator will want to make certain material available online, but also have it accessible to only a select few. Some examples of this might be student records, personalized information, email and even personal photo albums.
Of course there are many ways to restrict access to information ranging from web server configurations to third party programs. In this tutorial, we'll take a look at the basic theory behind a user authentication system using PHP.
Storing Passwords
Before we can begin coding with PHP, we need to first take a brief look at passwords. There are many different ways to manage and store a user's login ID and passwords, but one common method is to store them in a database.
For security purposes, the passwords themselves should not be stored in the database in a plain text manner. Instead, the password can be processed by a one-way, irreversible encryption or hashing function and then the jumbled result is what is actually stored. That means the password supplied later will need to be encrypted/hashed before we compare it with the stored value. If they both match then we know the password is good.
PHP's sha1 function should suffice for our purposes. It accepts a string and returns a 40 character hexadecimal hash representation. This hash cannot be converted back to the original string. The following is an example of sha1 in action:
Code :
// hide source code
// hide line numbers
// hide source code
// hide line numbers
1 <?php
2 $password = "secret";
3
4 echo $password;
5 /* displays secret */
6
7 $password = sha1($password);
8
9 echo $password;
10 /* displays e5e9fa1ba31ecd1ae84f75caaa474f3a663f05f4 */
11 ?>
We'll assume for this tutorial that a database table named Users exists which stores the username and passwords hashed with the sha1 function.
It's common mistake to not make the password column large enough to store the entire hash. Using sha1, the column should be 40 characters.
Getting the User Login
An HTML form is used to obtain the user's login credentials. The form displays 2 input fields--one to obtain the login ID and another to obtain the password.
Code :
// hide source code
// hide line numbers
// hide source code
// hide line numbers
1 <form action="validate.php" method="post">
2 <label for="userid">ID</label>
3 <input type="text" name="userid" id="userid" />
4 <br />
5 <label for="password">Password</label>
6 <input type="password" name="password" id="password" />
7 <br />
8 <input type="submit" name="submit" value="Submit" />
9 </form>
The userid input field accepts the user's login id while the password field will accept the user's password. The password field might show asterisks or dots as the value is entered, but remember that the form will send it's data in clear text. A secure connection should be made using HTTPS. For more information on that subject see my tutorial Generating Your Own Security Certificates For Use With Apache/HTTPS.
The form here submits its information to a script named validate.php as specified by the form's action attribute. It's that script that will be responsible for checking the user's login ID and password in the database and allowing the user to continue.
Processing the Login
The actual authentication can take place once we have the user's login ID and password. We need to encrypt or hash the password the same way it was initially done.
Code :
// hide source code
// hide line numbers
// hide source code
// hide line numbers
1 $user = $_POST["userid"];
2 $pass = sha1($_POST["password"])
With the ID and password value, we can query the database for any matching records. The following SQL statement is designed to return records where the login ID and password hash match.
SELECT * FROM Users WHERE User = '$user' AND Password = '$pass'
If the query returns a record set then the login credentials are valid and the user may have access to the protected information. If the query fails to return a record then the credentials are invalid and access is denied.
The validate.php script that would accomplish all of that might resemble the following:
Code :
// hide source code
// hide line numbers
// hide source code
// hide line numbers
1 <?php
2 /* get the incoming ID and password hash */
3 $user = $_POST["userid"];
4 $pass = sha1($_POST["password"]);
5
6 /* establish a connection with the database */
7 $server = mysql_connect("localhost", "mysql_user",
8 "mysql_password");
9 if (!$server) die(mysql_error());
10 mysql_select_db("myDatabase");
11
12 /* SQL statement to query the database */
13 $query = "SELECT * FROM Users WHERE User = '$user'
14 AND Password = '$pass'";
15
16 /* query the database */
17 $result = mysql_query($query);
18
19 /* Allow access if a matching record was found, else deny access. */
20 if (mysql_fetch_row($result))
21 echo "Access Granted: Welcome, $user!";
22 else
23 echo "Access Denied: Invalid Credentials.";
24
25 mysql_close($server);
26 ?>
Instead of simply echoing "Access Granted" or "Access Denied" as shown here, your script can set cookies or start sessions, redirect the user to the login form or perform whatever else is needed.
Persisting the Authentication
Once access to a resource has been granted to a user, it's typical for the access privileges to persist for a period of time. PHP sessions offer a nice way to carry information such as authentication throughout a series of pages. This way, a user won't have to provide a user ID and password each time a resource is accessed.
The validate.php script would initiate a session, set an access token and then redirect the user to the secured document.
Code :
// hide source code
// hide line numbers
// hide source code
// hide line numbers
1 <?php
2 if (mysql_fetch_row($result)) {
3 /* access granted */
4 session_start();
5 header("Cache-control: private");
6 $_SESSION["access"] = "granted";
7 header("Location: ./secure.php");
8 } else
9 /* access denied ? redirect back to login */
10 header("Location: ./login.html");
11 ?>
After which each secured resource would continue the session and check for the access token.
Code :
// hide source code
// hide line numbers
// hide source code
// hide line numbers
1 <?php
2 session_start();
3 header("Cache-control: private");
4 if ($_SESSION["access"] == "granted")
5 header("Location: ./secure.php");
6 else
7 header("Location: ./login.html");
8 ?>
I recommend Hermawan Haryanto's tutorial Using Sessions in PHP for more information on working with PHP sessions.
Conclusion
Authentication allows various resources to be published on the Internet but viewable only by those who can present the appropriate credentials. With the information presented in this tutorial you should be able to construct your own authentication system.
You might even want to organize your code in a set of functions or a class; the code can be written to be rather self-sufficient and then inserted in the top of each resource with include or require.
About The Author
Timothy Boronczyk lives in Syracuse, NY, where he works as an E-Services Coordinator for a local credit union. He has a background in elementary education, over 5 years experience in web design and has written tutorials on web design, PHP, Ruby, XML and various other topics. His hobbies include photography and composing music.
Donation:If you like our free quality work, make a donation by using Paypal and tell us what you would like to see improved on our site for the next few months. |
|
File Download
No comments yet













Page Info













