Main Page Content
Creating A Login Script With Php 4
In this article we're going to create a login script with PHP that will allow registered users to login to your site. With this method we'll make restricting certain areas of your site to registered users child's play.
What's the point?
There could be many reasons you want to restrict access to registered users only. Say you have a rating script on your site, yet you don't want unregistered users to be able to submit their rating (as they do here on evolt.org). You could require a user to be logged in before they could access the rating script by including a login check script at the beginning of a document.
Requirements
To use this script you must have access to PHP 4, and the PHP installation must be configured to allow sessions. We're going to use sessions with PHP 4 to check the user's input, and if it is indeed the information of a registered member, register this information as session variables so the script doesn't have to request their login info time and time again. It will create a session for them and "remember" the user until they log out.
Enough yappin', let's code it.
Start the Session
<?session_start(); // start session, duh.?><!-- header tags, edit to match your own, or include() template header file. --><html><head><title>Login</title><head><body><?
Alright, besides adding alittle header HTML in, the only useful bit in there is session_start() (click it). All this function does is initialise a session, or resumes the current one, bah, read the page. So now we have our session started, let's get it going.
Check Client
Next we need to check if the client is already logged in or not. If they are, leave them be, if they're not, pop up a login form:
if(!isset($username) !isset($password)) {// escape from php mode.?><form action="<?=$PHP_SELF?><?if($QUERY_STRING){ echo"?". $QUERY_STRING;}?>" method="POST"><p align="center">Members only. Please login to access this document.</p><table align="center" border="0"> <tr> <th>Username: </th> <th><input type="text" name="username"> </th> </tr> <tr> <th>Password: </th> <th><input type="password" name="password"> </th> </tr> <tr> <th colspan="2" align="right"><input type="submit" value="Login"></form> </th> </tr></table></body></html><?exit();}
OK now $username
and $password
are our session variables. These variables will be registered and be available to all scripts whilst our session is open. If they're not set, then the user isn't logged in and we need to set them before the client can access the document, so we present them with a form and ask them for their username and password. I also made it so if there's a query string, add it into the form action. Say a user requested index.php?action=mail but they're not logged in. When the login form is displayed, and they login, you want them to end up where they were heading (index.php?action=mail, not just index.php), they will.
Verify The Client
Next we need to register the session variables, if the user has just submit the login form then this bit of code will register them as session variables, and authenticate them.
// If all is well so far.session_register("username");
session_register("password"); // register username and password as session variables.// Here you would check the supplied username and password against your database to see if they exist.
// For example, a MySQL Query, your method may differ, obviously you would make a dataabse connection first.$sql = mysql_query("SELECT password FROM user_table WHERE username = '$username'");
$fetch_em = mysql_fetch_array($sql);$numrows = mysql_num_rows($sql);if($numrows != "0" & $password == $fetch_em["password"]) {
$valid_user = 1;}else {$valid_user = 0;}
OK first we use session_register() to register the client's username and password as session variables. Then we need to check if the username and password they supplied are valid. Bear in mind this is only an example, but say we have the below table in our database:
id | username | password |
---|---|---|
1 | fred | Mypass |
2 | bob | bobspassword |
3 | lace | letmein |
Now say bob is presented with the login form. He enters his username, bob, and his password, bobspassword. The script then registers these values as his session variables, then queries the database for a row where the username is bob and retrieves the password, it also counts the number of rows where the username is bob. Now if all goes well, $numrows
should contain the int value of 1
, $fetch_em["password"]
will contain the user's password.
if($numrows != "0" & $password == $fetch_em["password"]) {
If the number of rows affected is not equal to zero and the password the user supplied is equal to the password retrieved from their database row, their information is correct, making them a valid user. If the above logic isn't true, set $valid_user
to zero.
If information is incorrect
If the user enters incorrect information, up to now all the script does is check if the session variables are registered or not, so we need to add in a little bit to request their information again:
// If the username exists and pass is correct, don't pop up the login code again.// If info can't be found or verified....if (!($valid_user))
{session_unset(); // Unset session variables.session_destroy(); // End Session we created earlier.// escape from php mode.?><form action="<?=$PHP_SELF?><?if($QUERY_STRING){ echo"?". $QUERY_STRING;}?>" method="POST"><p align="center">Incorrect login information, please try again. You must login to access this document.</p><table align="center" border="0"> <tr> <th>Username: </th> <th><input type="text" name="username"> </th> </tr> <tr> <th>Password: </th> <th><input type="password" name="password"> </th> </tr> <tr> <th colspan="2" align="right"><input type="submit" value="Login"></form> </th> </tr></table></body></html><?exit();}
here we use session_unset() to unset the registered session variables and session_destroy() to kill the session completely, just to make sure. Then we present the user with a login form telling them the supplied information was invalid, please try again.
Logging Out
Once the user is logged in, each time they try to access a protected document the above script will recognise their session and allow them to access. It is wise to have a logout script that simply terminates the session and offers them a link to login again or go to "home", see below:
<?session_start();session_unset();session_destroy(); // destroy session.?><html><head><title>Logged Out</title></head><body><p align="center">You have been successfuly logged out.</p><p align="center"><a href="members.php">Log back in</a> <a href="index.php">Go to homepage</a></p></body></html>
All we have done is destroyed the session completely and informed the user they are now "logged out".
The Scripts
login.php
<?session_start(); // start session.?><!-- header tags, edit to match your own, or include template header file. --><html><head><title>Login</title><head><body><?if(!isset($username) !isset($password)) {// escape from php mode.?><form action="<?=$PHP_SELF?><?if($QUERY_STRING){ echo"?". $QUERY_STRING;}?>" method="POST"><p align="center">Members only. Please login to access this document.</p><table align="center" border="0"> <tr> <th>Username: </th> <th><input type="text" name="username"> </th> </tr> <tr> <th>Password: </th> <th><input type="password" name="password"> </th> </tr> <tr> <th colspan="2" align="right"><input type="submit" value="Login"></form> </th> </tr></table></body></html><?exit();}// If all is well so far.
session_register("username");
session_register("password"); // register username and password as session variables.// Here you would check the supplied username and password against your database to see if they exist.
// For example, a MySQL Query, your method may differ.$sql = mysql_query("SELECT password FROM user_table WHERE username = '$username'");
$fetch_em = mysql_fetch_array($sql);$numrows = mysql_num_rows($sql);if($numrows != "0" & $password == $fetch_em["password"]) {
$valid_user = 1;}else {$valid_user = 0;}// If the username exists and pass is correct, don't pop up the login code again.
// If info can't be found or verified....if (!($valid_user))
{session_unset(); // Unset session variables.session_destroy(); // End Session we created earlier.// escape from php mode.?><form action="<?=$PHP_SELF?><?if($QUERY_STRING){ echo"?". $QUERY_STRING;}?>" method="POST"><p align="center">Incorrect login information, please try again. You must login to access this document.</p><table align="center" border="0"> <tr> <th>Username: </th> <th><input type="text" name="username"> </th> </tr> <tr> <th>Password: </th> <th><input type="password" name="password"> </th> </tr> <tr> <th colspan="2" align="right"><input type="submit" value="Login"></form> </th> </tr></table></body></html><?exit();}?>
logout.php
<?session_start();session_unset();session_destroy(); // destroy session.?><html><head><title>Logged Out</title></head><body><p align="center">You have been successfuly logged out.</p><p align="center"><a href="members.php">Log back in</a> <a href="index.php">Go to homepage</a></p></body></html>
Now to require a user to log in, simply include the login script at the top of a php page.
include($DOCUMENT_ROOT .'/includes/login.php'); // or wherever yours is.
Bear it in mind that the session places a cookie on the client's machine, so if they are not accepting cookies this script will have problems logging them in. There is a work-around for this by using the session ID (session_id()) and passing it along in the query string, through form and links and such, and the variable is only set when a cookie cannot be set, providing an easy way to check if a user is accepting cookies or not. For more information see php.net's sessions reference.
Inspiration
In this article the script is used to require a user to login (as you may have noticed). This is just one application, you could have it so there is only one valid username and password pair and use it as an admin script, restrict access to each admin document by including it at the top of each file. I used this method in a guestbook script I recently wrote.
Hint: make sure you include the login script in your PHP document before any output, as you would use the setcookie() function, unless you want a "Headers already sent" error.
Look Into It
Sessions with PHP 4 is a powerful and easy-to-use method to register variables across requests. I recommend you look into sessions and learn more about them. As with all things it has advantages and disadvantages. Problems arise in certain circumstances, users have cookies off, but that's all part of building a compatible-for-all website. Have a play around on your personal server, or your host, you'll like it.
Bibliography
If you're curious and want to learn more about this nifty feature in PHP 4 visit php.net: