Sign in? or Create account?

Articles

Creating A Usable PHP/MySQL Login Application

by Mr. William Maker

 

The challenge of creating a working login form in PHP is making sure the server knows that the user's login is persistent throughout a certain field of pages. This article examines the use of the global $_SESSION variable as a way of allowing and disallowing access to any number of pages. This tutorial assumes the reader is already familiar with some basic PHP and MySQL.

The four pages implemented are as follows:

  1. login.php
  2. menu.php
  3. page1.php (will require a user to be logged in to view)
  4. page2.php (will require a user to be logged in to view)

Also, we will write one class that will be used by the three pages above: session.php

Any attempts to access page1.php or page2.php without being logged in will result in the user viewing a login form, rather than the page's actual content. Once logged in, the user will have an additional option to log out.

 

First, we need a table in our MySQL database to work with as well as a test username and password. The process is outlined below, and shown in detail through example.

1. Log in to MySQL

wmaker@server0:~$ mysql -u root -p
Enter password:
mysql>

2. Select your database.

A. You already have a database set up.
mysql> use testdb;
Database changed
B. You need to create a database.
mysql> create database testdb;
mysql>

3. Create a users table

mysql> create table users (id int primary key auto_increment, username
text, password text);
Query OK, 0 rows affected (0.01 sec)
mysql>

4. Insert a test user

mysql> insert into users (username, password) values ('testuser',
MD5('password'));
Query OK, 1 row affected (0.00 sec)

 

Now that we have a username and password located in a MySQL database, we can begin to build a basic layout that you can modify to suit the needs of your web application. First let us begin by creating a menu that contains our pages and a login/logout option that will swap by determining if a user is logged in or out.

menu.php
if ($s->checksession())
	echo '<a href="logout.php">logout</a><br />';
else
	echo '<a href="login.php">login</a><br />';

echo '<a href="page1.php">page 1</a><br />';
echo '<a href="page2.php">page 2</a><br />';

The only new code is the $s->checksession() member function on some object $s. We have not yet defined this object, however we can pretend this function exists until we do in fact write our session.php class.

We see that if a user is logged in, a link to login.php?logout is available. This link will log a user out. We will complete the login.php after page1.php and page2.php, but before our session.php class.

The checksession() function will return a true or false value. This tells each of our pages whether a user is logged in or not.

 

Next, create two pages with a slight variation in content so we can tell the difference between the two.

page1.php
include('session.php');

$s = new session();
$s->startsession();

if ($s->checksession()) {
	include('menu.php');
	echo "We are logged in, this is Page 1 content.";
} else {
	include('login.php');
}
page2.php
include('session.php');

$s = new session();
$s->startsession();

if ($s->checksession()) {
	include('menu.php');
	echo "We are logged in, this is Page 2 content.";
} else {
	include('login.php');
}

We can see that each of these pages creates a session object that is located in session.php. Developing this class will be our last step. After the object is created the startsession() member function is run. This is vital at the beginning of each page you wish to protect with your login application. If you do not start the session by running the startsession() member function the PHP page will not know how to resume the persistent login that was created.

Once again, we use the checksession() member function to determine the status of the user. If the user is logged in, it displays the protected content; otherwise, the login form is displayed.

Now, we need to create the login form, and process the information once it is submitted.

login.php
include('session.php');

$s = new session();
$s->startsession();

function show_form($s) {
	include('menu.php');
	
	?>	
	<table>
		<tr>
			<td>Username:</td>
			<td>&nbsp;</td>
		</tr>
		<tr>
			<td>Password:</td>
			<td>&nbsp;</td>
		</tr>
		<tr>
			<td>&nbsp;</td>
			<td><input type="submit" value="Login" /></td>
		</tr>
	</table>
	<?
}

function show_logged_in($s) {
	include('menu.php');
	echo "You are logged in...";
}

function check_get_vars($s) {
	if (isset($_GET['done']))
		$s->authenticate($_POST['username'], $_POST['password']);
	
	if (isset($_GET['logout']))
		$s->logout();
}

function display($s) {
	if ($s->checksession())
		show_logged_in($s);
	else
		show_form($s);
}

check_get_vars($s);
display($s);

As stated before, the session object needs to be declared and the startsession() member function must be run at the beginning of every PHP file attached to our web application.

Our show_form($s) function displays the menu, a username textbox, a password textbox and a submit button and posts it to login.php?done. We use the done variable to detect when someone has submitted a username and password.

Our show_logged_in($s) function displays the menu and also a brief message letting the user know they are now logged in.

The check_get_vars($s) function checks two $_GET variables from the URL. If $_GET['done'] exists then the user has posted some log in information that we need to validate. If $_GET['logout'] exists then a user has chosen to log out. $s->authenticate() is used to check our database to determine if the credentials the user entered are valid. $s->logout() logs the user out.

Finally, the display($s) function checks to see if the user is logged in and displays either runs show_form($s), or runs show_logged_in($s).

When login.php is included or run, it checks our $_GET variables and then displays the appropriate content.

session.php

Last, we need to create our session.php class. This code is the heart of the login web application. First read through the code carefully. Then analyze what each piece does:

require_once('session.php');

$s = new session();
$s->startsession();

function show_form($s) {
	include('menu.php');
	
	?>
	<form action="?done" method="post">
	<table>
		<tr>
			<td>Username:</td>
			<td><input type="text" name="username" /></td>
		</tr>
		<tr>
			<td>Password:</td>
			<td><input type="password" name="password" /></td>
		</tr>
		<tr>
			<td> </td>
			<td><input type="submit" value="Login" /></td>
		</tr>
	</table>
	</form>
	<?
}

function show_logged_in($s) {
	include('menu.php');
	echo "You are logged in...";
}

function check_get_vars($s) {
	if (isset($_GET['done']))
		$s->authenticate($_POST['username'], $_POST['password']);
	if (isset($_GET['logout']))
		$s->logout();
}

function display($s) {
	if ($s->checksession())
		show_logged_in($s);
	else
		show_form($s);
}

check_get_vars($s);
display($s);

 

First, modify the $dbhost, $dbname, $dbuser and $dbpass variables to fit your setup.

The connectdb() function will be used to connect to our database and select the database with which you created the users table earlier.

The disconnectdb() function will be used to close our MySQL connection after our query has run.

The startsession() function is the important function that is included at the beginning of each of our protected pages and it runs the PHP global function session_start() that initializes all our global $_SESSION variables.

The setsession() function actually sets our $_SESSION variables when a user logs in or out. $_SESSION['username'] is set to the user's username, $_SESSION['id'] is set to the users id number and $_SESSION['authorized'] is set to 0 if the user is not logged in, or 1 if the user is logged in.

The logout() function runs setsession(0, '', 0); which sets the id to 0, the username to blank and authorized to 0.

The authenticate($username, $password) function is run from our login.php page. This queries our database to determine if a user's credentials are right or wrong. If they are right, setsession($row->id,$row->username,1) is run and the user is logged in. If they are incorrect, the authorized variable remains 0 and the user is not logged in.

 

This concludes the tutorial. If you follow the SQL instructions above and copy/paste each set of code into the appropriate file you will have a working example to experiment with.

As an exercise, try adding a group table to your database and a group id column to your users table. Then adapt the session.php class to work with groups of users to display guest, regular user, and administration content.

Back to Top Back to Top

 

About the author

Mr. William Maker

Mr. William Maker (USA)

Mr. Maker expects to graduate from the University of Oklahoma majoring in Mathematics in May 2008. William has extensive training and experience in multiple operating systems and languages including Linux, Unix, Microsoft Windows, MySQL, C++, HTML, PHP and others. He has utilized his education and skills working for the University of Central Oklahoma, Hertz Corporation and others.

 

© 2007-2010 Samenmais Corporation™