3:24 AM

PHP : Simple Login/Logout System with Sessions

posted under by FR3@K | Edit This
This tutorial will help you create a really basic user login system.

Here is what we are going to do in English: The user can login with an email & password. If the email and password match then create a session and allow the user to access the private members page. If an unauthorized user tries to access the members page without logging in, they will be forced to return to the login page.

So lets start off by creating a new database to store emails and password.

CREATE DATABASE test;

Next we can create a table in the database to store the users email and password. If you can’t figure out how to create the database and table, I recommend Googling for some general MySQL & PHPMyAdmin tutorials. They will help you a lot.

CREATE TABLE usersystem
(
id int AUTO_INCREMENT NOT NULL,
email varchar(120) NOT NULL,
password varchar(30) NOT NULL,
PRIMARY KEY (id)

);


INSERT INTO usersystem(email,password)
VALUES ('test@brendewilson.com','123');


INSERT INTO `usersystem` (email,password)
VALUES ('anothertest@brendenwilson.com','1234');

If the SQL code above was correctly entered into the ‘test’ database then you will have three columns in the database, ID, Email and password. The ID field is there to identify each entry as unique. Some people might have two accounts with the same email and if that happens, the ID field will allow us to differentiate between the two. The primary key part says that the ‘ID’ field will be unique for every row. The last two rows insert test data into the database so we can test the login system when it is finished.

Now create a file called include.php. This file will store all the code we want place at the top of every page.

<?php

session_start();



$host = "localhost";

$username = "USERNAME";

$password = "PASSWORD";

$db = "test";

@mysql_connect($host,$username,$password) or die ("error");

@mysql_select_db($db) or die("error");

?>



We are going to include this file at the very beginning of every page we setup. It will start the session and then connect your page with the MySQL database.

One thing to note: If you get an error saying that the headers were already sent, your start_session() probably wasn’t at the very top of the page. The start_session() has to be at the very top of the page.

Now create a login.php with this code.

<?php

require_once('include.php');

$error = '';

$form = $_POST['submit'];

$email = $_POST['email'];

$password = $_POST['password'];



if( isset($form) ) {



if( isset($email) && isset($password) && $email !== '' && $password !== '' ) {



$sql = mysql_query("SELECT * FROM `usersystem` WHERE email='$email' and
password='$password';");



if( mysql_num_rows($sql) != 0 ) { //success

$_SESSION['logged-in'] = true;

header('Location: members.php');

exit;

} else { $error = "Incorrect login info"; }

} else { $error = 'All information is not filled out correctly';}

}

?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />

<title>Login</title>

</head>

<body>

<form action="<?php $PHP_SELF; ?>" method="post" >

Email<br />

<input name="email" type="text" value="<?php echo "$email";?>" /><br /><br />

Password<br />

<input name="password" type="password" /><br />

<input name="submit" type="submit" value="Log In" />

</form>

<?php

echo "<br /><span style=\"color:red\">$error</span>";

?>

</body>

</html>




Lets break this code down so it a little easier to understand.

In English, here is what the code means:
Include the include.php file.
Set the $error variable to a blank value.
If the form was submitted, put the values into the variables, $form, $email, $password so we can use them later.
If the form is submitted....
And the email and password fields are filled out and they aren't blank...
Check to see if there are any rows in the database that have a matching email and password.
If there are, that means the user entered a matching email and password.
Set the session.
Change the page to members.php.
And stop running the php code.
If the user didn't enter a matching email and password, throw an error.

Now create the members.php. This page will only be available to people who have signed in on the prior page. Here is the code that goes in that page.

<?php

require_once('include.php');

// is the one accessing this page logged in or not?

if ( !isset($_SESSION['logged-in']) || $_SESSION['logged-in'] !== true) {



// not logged in, move to login page

header('Location: login.php');

exit;

}

?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />

<title>Freak's Blog</title>

</head>

<body>

Sweet you lgged in.

<a href="logout.php">logout</a>

</body>

</html>




This block of code is actually pretty simple. Just like on all the other pages, we include the include.php file at the top. The include.php file sets the session up and connects to the MySQL database. Then, if the appropriate session is not set (the user didn’t login), we move the user to the login page and exit the code. If the users has logged in, and their session is appropriately set, they will see the rest of the page. This pages format can be copied to create additional hidden pages.

Now to the final step. Create logout.php and enter this code:

<?php

session_start();

// if the user is logged in, unset the session

if (isset($_SESSION['logged-in'])) {

unset($_SESSION['logged-in']);

}

// now that the user is logged out,

// go to login page

header('Location: login.php');

?>




This page doesn’t have any HTML in it. The first line starts the session, and then if the user is logged in, the session will be destroyed and the user will be redirected to the login page.

I hope you enjoyed the tutorial. Please leave me feedback through the comment system below so I can improve my tutorials in the future.

0 comments

Make A Comment
top