Simple Login, Logout & Sessions in PHP
Tuesday, June 8, 2010 1:34I am going to provide an overview of how I got the login system on my website to work. I will start by mentioning this should not be used to protect sensitive information (ie: health records) because it uses a table you add to your database. The table I used is:
| Column | Data Type | Null | Primary Key | Other |
|---|---|---|---|---|
| user_id | int | No | PK | Auto Increment |
| username | varchar(11) | No | Unique | |
| password | varchar(32) | No | ||
| permission | enum(‘ADMIN’,'GUEST’) | No |
When adding a new user you have to make sure to apply the function MD5 to the value being added to the password field so it is not stored in plain text. The reason for the 32 character length is that the MD5 value generated is 32 characters long. I made the username column unique so that no user will have the same name. I use the permissions column by storing the username of who is logged into the current session so that I can determine if they are an administrator (ADMIN) so that I provide the user the option to insert, delete, and update records in the database.
Now that you have an idea of what I am trying to do, we have to use this table and the functionality PHP provides to create our login system. To make this work you will need three or four files (index.php, login.php, checkLogin.php, logout.php) which I will show you and explain some of the logic behind them.
Request Credentials
The first stage is to create your index.php file, which will be the first page your users see, before entering your ‘restricted’ area, to provide their credentials to gain access.
index.php
————————————————————————-
<?php
$error = “Please login to access the database.”;
if(isset($_REQUEST["error"])){
$error = $_REQUEST["error"];
}
?>
<html>
<head>
<title>Login</title>
</head>
<body>
<center>
<?php
echo $error;
?>
<form method=”POST” action=”login.php”>
Username: <input type=”text” name=”username” size=”20″>
Password: <input type=”password” name=”password” size=”20″>
<input type=”submit” value=”Submit” name=”login”>
</form>
</center>
</body>
</html>
————————————————————————-
The first section before the open html tag is used to see if we (the programmers) have passed a variable error with a value to be used within this page. The rest is to provide a basic user interface to prompt the user for their username and password to be submitted. The action of our post is login.php, which is where the values of our form will be sent to for processing, which leads into the second step.
Verify Credentials
Now we have to check to make sure the username and password provided is valid, which is done in login.php.
login.php
————————————————————————-
<?php
//check that the user is calling the page from the login form and not accessing it directly
//and redirect back to the login form if necessary
if (!isset($_POST['username']) || !isset($_POST['password'])) {
header( “Location: index.php?error=You must login first” );
}
//check that the form fields are not empty, and redirect back to the login page if they are
elseif (empty($_POST['username']) || empty($_POST['password'])) {
header( “Location: index.php?error=Username or password was blank” );
}
else{
//convert the field values to simple variables
//add slashes to the username and md5() the password
$user = addslashes($_POST['username']);
$pass = md5($_POST['password']);
//set the database connection variables
$dbHost = “ip address”;
$dbUser = “username”;
$dbPass = “password”;
$dbDatabase = “database name”;
//connect to the database
$db = mysql_connect(“$dbHost”, “$dbUser”, “$dbPass”) or die (“Error connecting to database.”);
mysql_select_db(“$dbDatabase”, $db) or die (“Couldn’t select the database.”);
$result=mysql_query(“select * from user where username=’$user’ AND password=’$pass’”, $db);
//check that at least one row was returned
$rowCheck = mysql_num_rows($result);
if($rowCheck > 0){
while($row = mysql_fetch_array($result)){
//start the session and register a variable
session_start();
session_register(‘user’);
$_SESSION['l_user'] = $user;
//successful login code will go here…
//we will redirect the user to another page where we will make sure they’re logged in
header( “Location: main.php” );
}
}
else {
//if nothing is returned by the query, unsuccessful login code goes here…
header( “Location: index.php?error=Check username and password” );
}
}
?>
————————————————————————-
Firstly, we gather the values for the username and password that we passed from our login form. Then check to make sure that neither is empty, and if they are then we know it is not valid and we redirect the user back to the login form with header( “Location: index.php?error=Username or password was blank” );, otherwise we continue and md5 the password for comparison with the value stored in the database.
We then connect to the database and select the username and md5 version of the password from the user table, if the number of rows returned is 1 (shouldn’t be more as we have the username being unique) then they are a valid user and we start a session (session_start()) and register the session (register_session($user)) providing their username as a parameter. For the privileges to work we need to store their username in the session ($_SESSION['l_user'] = $user). Lastly, we redirect them to the first page you want them to see once logged in, which in this example is main.php.
If they are not a valid user then we would redirect them back to the login page with a message stating that fact.
Protect Pages
Now that the user is logged in we need a way to distinguish on each page if a valid user is logged in so they can view the page or redirect them to the login page if they are not.
checkLogin.php
————————————————————————-
<?php
//start the session
session_start();
//check to make sure the session variable is registered
if(session_is_registered(‘user’)){
//the session variable is registered, the user is allowed to see anything that follows
}
else{
//the session variable isn’t registered, send them back to the login page
header( “Location: index.php?error=You have to be logged in to view this website” );
}
?>
————————————————————————-
Firstly we need to have start_session() to ensure that we are working within the proper session, and then we check to see if the user is registered and if they are we allow them to view the page, otherwise we send them to the login page (index.php) and use the error variable, mentioned in index.php to display the message and have them login. If you wish to add more functionality you could, upon having a successful login, have it redirect back to the page they were trying to access.
Remember, you have to include this page at the top of EVERY page you wish the user to be logged in to view, and it has to be the first thing (prior to any other code) so that it gets processed correctly.
Utilizing Permissions
I took advantage of the fact that a user was an admin or a guest by checking the permissions value of the current logged in user prior to displaying links to insert, delete, or update records within the database. If the check came back that they were an admin I would provide them with a link, otherwise I would place nothing making my code something like:
<?php
$user = $_SESSION['l_user'];
if(isAdmin($user))
echo "<p><a href='inserthuman.php'>New Record</a></p>";
?>
Logout
Lastly, now that we have a logged in user, we need a way to log them out and end their session, so that if they (or another user) try to access any pages login credentials will need to be provided.
logout.php
————————————————————————-
<?php
//start the session
session_start();
//brute force it… destroy it all… because checks were not working
session_unregister(‘user’);
session_unset();
session_destroy();
$_SESSION = array();
header( “Location: index.php?error=You have successfully logged out” );
?>
————————————————————————-
Again we need to make sure that we are working within the correct session (session_start()). First you need to unregister the user and destroy the session. Afterwords, to really make it work, I found that I needed to destroy all data in the $_SESSION variable, so I destroyed its current contents by reassigning a new empty array to the variable.
Lastly, now that we have taken care of the session we will redirect them back to the login screen stating that they are successfully signed out.
Conclusion
With these elements all put in place I was able to create a successful login system for my database front-end. It does not do anything fancy, like allow for administering user accounts, setting permissions (beyond the basic ADMIN or GUEST), etc. but this could be expanded to incorporate some advanced functions if necessary.