SEARCH
Newsletter
Subscribe to get design tips, latest trends, free stuff and more.
It doesn't look like an e-mail address

hosting

  Web Programming PHP Cookies / Remember Me

Cookies / Remember Me

Joseph Skidmore PHP Aug 07, 2006

Cookies / Remember MeYou may have seen on some sites they have login forms with a checkbox underneath saying 'Remember Me' and when ticked it does something magic ... when you go back to the page it does remember you ... but how? Easy!

Using cookies to remember a user

When you tick the little Remember Me box it sets 2 cookies on your computer, one that stores your username and password, when you return to the site it checks the information stored within these cookies, if they are correct it logs you straight in without you having to manually log in yourself.

To start with we need to create our database called 'cookie' that will store the user's login information; Insert the following code into your newly created database.

SQL Code

CREATE TABLE 'login' (
'ID' int(11) NOT NULL auto_increment,
'user' varchar(30) default NULL,
'pass' varchar(30) default NULL,
KEY 'ID' ('ID')
) TYPE=MyISAM AUTO_INCREMENT=2 ;

INSERT INTO 'login' VALUES (1, 'username', 'password');

Next is our index page, this page first checks to see whether the cookie exists, if so it checks the information against the data inside the database, if correct sets the SESSION 'loggedin' to 1 and forwards the user to the admin page.

index.php

<?php
session_start();

if(isset($_COOKIE['Joe2Torials']))
// If the cookie 'Joe2Torials is set, do the following;
{
$dbHost = 'localhost';
// Database Connection Details - Host
$dbUser = 'username';
// Database Connection Details - Username
$dbPass = 'password';
// Database Connection Details - Password
$dbname = 'cookie';
// Database Connection Details - Database Name


$username = $_COOKIE['Joe2Torials']['username'];
// Select the username from the cookie
$password = $_COOKIE['Joe2Torials']['password'];
// Select the password from the cookie

$db = mysql_connect($dbHost,$dbUser,$dbPass); // Connection Code
mysql_select_db($dbname,$db); // Connects to database

$query = "SELECT user, pass FROM login WHERE user = '$username' AND pass = '$password'";
$result = mysql_query($query, $db);
if(mysql_num_rows($result))
// If the login information is correct do the following;
{
$_SESSION['loggedin'] = 1;
// Set the session 'loggedin' to 1 and forward the user to the admin page
header('Location: http://www.domain.com/admin.php');
exit();
}
}

/* If the cookie doesn't exist or the login
information stored within the cookies
are wrong show the login form.
*/
?>

<form method="post" name="cookie" action="process.php">

<p><label for="username">Username : <input type="text" name="username" id="username" /></label></p>
<p><label for="password">Password : <input type="password" name="password" id="password" /></label></p>
<p><input type="checkbox" name="setcookie" value="setcookie" /> Remember Me</p>

<p><input type="submit" name="submit" value="Submit" /> <input type="reset" name="reset" value="Reset" /></p>
</form>

<?php
if (isset($_GET['error']) AND !empty($_GET['error']))
{
echo 'Invalid login data supplied. Please try again.';
}
?>

NOTE: Please remember to change the name of the cookie from Joe2Torials to the name of your site.

If the username and/or password are incorrect it shows the login form for the user to log in. Once submit has been pressed the form sends the information to process.php for processing.

process.php

<?php
session_start(); // Shows we are using sessions

$dbHost = 'localhost';
$dbUser = 'root';
$dbPass = '';
$dbname = 'cookie';

$username = $_POST['username']; // Gets the inputted username from the form
$password = $_POST['password']; // Gets the inputted password from the form
$time = time(); // Gets the current server time
$check = $_POST['setcookie']; // Checks if the remember me button was ticked

$db = mysql_connect($dbHost,$dbUser,$dbPass); // Connection Code
mysql_select_db($dbname,$db); // Connects to database

$query = "SELECT user, pass FROM login WHERE user = '$username' AND pass = '$password'";
$result = mysql_query($query, $db);
if(mysql_num_rows($result)) { // If the username and password are correct do the following;
$_SESSION['loggedin'] = 1; // Sets the session 'loggedin' to 1

if($check) {
// Check to see if the 'setcookie' box was ticked to remember the user
setcookie("Joe2Torials[username]", $username, $time + 3600); // Sets the cookie username
setcookie("Joe2Torials[password]", $password, $time + 3600); // Sets the cookie password
}

header('Location: http://www.domain.com/admin.php'); // Forwards the user to this URL
exit();
}
else // If login is unsuccessful forwards the user back to the index page with an error
{
header('Location: http://www.domain.com/index.php?error=1');
exit();
}
?>

process.php is the part of the script that checks the users login information (if the cookie wasn't set in the first place) and then does the check to see whether the 'Remember Me' box was ticked. If the box was not ticked it simply logs the user in ... if the box was ticked then the script sets the cookies containing the username and password and then logs the user in.

admin.php

<?php
session_start();

if(!isset($_SESSION['loggedin'])) {
// If the session 'loggedin' is NOT set forward the user back to the login form with the error set
header('Location: http://www.domain.com/index.php?error=1');
exit(); // Otherwise show the rest of the page (admin section)
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html lang="en">
<head>

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

<title>Admin Section</title>

</head>
<body>

<p>Welcome to the admin section. <a href="/img_articles/9107/logout.php">Log out</a>.</p>

</body>
</html>

This is simply the admin section, at the top of the page is the check to see whether the SESSION is set (if login information is correct then this will be yes). If not then it will forward the user back to the login form with an error set.

logout.php

<?php
session_start();
session_unset();
session_destroy();
if(isset($_COOKIE['Joe2Torials'])) // If the cookie 'Joe2Torials is set, do the following;
{
$time = time();
setcookie("Joe2Torials[username]", $time - 3600);
setcookie("Joe2Torials[password]", $time - 3600);
}
header('Location: http://www.domain.com/index.php');

exit();
?>

As you can see with logout.php we check again to see whether the cookie is set, if the cookie isn't set we go ahead and destroy the session, if the cookie however is set we set 2 more, but why? Simple, it isn't possible to just delete a cookie so we must overwrite it with blank information, thus removing any content that was previously stored within. But what's with the $time - 3600 I hear you say! Cookies can be set with expiry dates/times, this is the only way they can be removed (apart from manually) so we set the time to expire -3600 seconds ago ... meaning they are already out of date when we set them and should remove themselves. (Not always straight away though).

And there you have it, a simple and effective way to remember user's login information. Please note: In order to make this script truly safe you will need to encrypt the stored passwords ... a tutorial on this coming soon!

subscribe to newsletter