Php User Login With Sessions

Padlock

This is a tutorial more or less on principles for sessions with PHP. It is more about the big picture, and meant as a stepping stone for further exploration.

The principal behind a user log in is simple, Don’t show private or secured information to non-members.

By using sessions you can:

  • Secure content from others.
  • Show custom content to members.
  • Remember user settings
  • And much more!

What we will do

  1. First we will need to log in to the site,
  2. Check to see if the log in is correct,
  3. If the log in was correct then we will allow access to our site, otherwise we will deny access,
  4. If the user leaves the site after a successful log in then we will allow access again without prompting for log in again.

Lets get started

I will cover the basic elements and supply my working source with this post so don’t worry if if you are missing some surrounding code that might make sense.

To start off we need to create a simple database. Something simple enough to hold a user name along with a password.

CREATE TABLE IF NOT EXISTS `members` (
	`id` int(4) NOT NULL auto_increment,
	`username` varchar(100) NOT NULL default '',
	`password` varchar(65) NOT NULL default '',
	PRIMARY KEY (`id`)
);

Now that the database has been created you need to have a user name and password to test against. Start off by inserting the user name and password “admin“. Make sure the password is inserted as SHA1. If its easier use the following SQL in your PHPMyAdmin.

INSERT INTO `members` VALUES(1, 'admin', 'd033e22ae348aeb5660fc2140aec35850c4da997');

Now that we have some credentials in the database we need a way to login.

<form name="form" method="post" action="index.php?action=check">
	<h4>Member Login:</h4>
	<label for="username">Username:</label>
	<input type="text" name="username" />
	<label for="password">Password:</label>
	<input type="password" name="password" />
	<input type="submit" value="Login" name="Submit" />
</form>

Every page that will use sessions needs to have session_start(); at the top of the page.

The form will post to another chunk of code that is in charge of checking weather or not the login was correct.

Because the password has been encrypted using SHA1 we have to encrypt the users input using he same method.

// username and password sent from form
$username=$_POST['username'];
$password=$_POST['password'];

$clean_username = strip_tags(stripslashes(mysql_real_escape_string($username)));
$clean_password = sha1(strip_tags(stripslashes(mysql_real_escape_string($password))));

$sql="SELECT * FROM members WHERE username='$clean_username' and password='$clean_password'";
$rs = mysql_query($sql) or die ("Query failed");

$numofrows = mysql_num_rows($rs);

if($numofrows==1){
	session_register("username");
	header("location:index.php?action=yes");
}
else {
	header("location:index.php?action=no");
}

Using the $_post[] array we will capture and assign our user name and password to matching variables. It is a good idea to do some cleaning to these variables. It is common for login scripts to bear the brunt of any exploits. Using strip_tags() stripslashes() mysql_real_escape_string() will help protect against these threats.

Our password must be encoded using sha1(). We will now compare the encrypted values with each other.

The SQL statement will return the results. Because the user name will be unique and the password encrypted we should be returned one row. This is important to know. If the user name existed more than once it is possible for the password to also exist more than once. This would return 2 and cause an error. In this case none of those users would gain access.

If we logged in correctly then we will set the session using session_register("username"); and redirect to the secured content. If not we will deny access and send the user back to the login screen.

We could at this point set other session variables like expiry time, but that’s a little outside the scope of this basic example.

It is time to update the default login screen. Add the following code above the long in screen. We have set the session variable user name. so we ill see if it has been set, if it has then redirect to the secure content bypassing the login screen.

if(isset($_SESSION['username'])){
	header("location:index.php?action=yes");
}

Every secure page should have the following code testing to see if the session variable has been set.

if(!isset($_SESSION['username'])){
	header("location:index.php?action=no");
}

Using the !isset() we will only act if the session variable has not been set.

Whats next?

We can now log in, check if the log in was successful acting accordingly. We have also secured our content in case that a non registered user or user who has logged out can not gain access to the secured information.

The last thing to do is allow the user to log out.’

session_destroy();
header("location:index.php");

Now the session has been destroyed the user will be redirected to the main log in page.

session_start();
//DB Connection information
$dbname="php_sessions";
$dbuser="root";
$dbpwd="";
$host="localhost";
// Connect to the database
$cid = mysql_connect($host,$dbuser,$dbpwd);
if (!$cid) { print "ERROR: " . mysql_error() . "n";    }
mysql_select_db("$dbname") or die(mysql_error());

switch ( $_GET['action'] ) {
	case "logout":
		session_destroy();
		header("location:index.php");
	break;
	case "no":
		echo '<h2>You <strong>NOT</strong> loged in.</h2>';
	break;
	case "yes":
		if(!isset($_SESSION['username'])){
			header("location:index.php");
		}
		echo '<h2>You <strong>ARE</strong> loged in.</h2>';
	break;
	case "check":
		$username=$_POST['username'];
		$password=$_POST['password'];
		
		$clean_username = strip_tags(stripslashes(mysql_real_escape_string($username)));
		$clean_password = sha1(strip_tags(stripslashes(mysql_real_escape_string($password))));
		
		$sql="SELECT * FROM members WHERE username='$clean_username' and password='$clean_password'";
		$rs = mysql_query($sql) or die ("Query failed");
		
		$numofrows = mysql_num_rows($rs);
		
		if($numofrows==1){
			session_register("username");
			header("location:index.php?action=yes");
		}
		else {
			header("location:index.php?action=no");
		}
	default:
		if(isset($_SESSION['username'])){
			header("location:index.php?action=yes");
		}
		?>
		<form name="form" method="post" action="index.php?action=check">
			<h4>Member Login:</h4>
			
			<p><label for="username">Username:</label><br />
				<input type="text" name="username" /></p>
			<p><label for="password">Password:</label><br />
				<input type="password" name="password" /></p>
			<p><input type="submit" value="Login" name="Submit" /></p>
		</form>
	<?
	break;
	}
?>
<p><a href="index.php?action=login">Log-in</a> | <a href="index.php?action=logout">Log-out</a></p>

Enjoy.

Signup for my mailing list

Receive other rambings like this on design, code, and some times food.