PHP is open source scripting language. It\'s widely used to develop web applications.  Home Web Programming PHP Cookies / Remember Me

Cookies / Remember Me


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!

To download a pre-written Cookies Remember Me Script click here: Pre-Written Cookies Remember Me Script



Author's URL: Joseph Skidmore
PHP is open source scripting language. It\'s widely used to develop web applications. More PHP Tutorials: Featured Materials | Fresh Materials | More PHP Tutorials at LearnPHP.org

Reader's comments
comments diyan December 02, 2011 says:
hi great can you show how to display user who have logged in in the admin
Reply
comments Sujeesh October 21, 2011 says:
Thanks
Reply
comments 5 February 04, 2011 says:
5
Reply
comments meemeo January 14, 2011 says:
like O/
Reply
comments n30cr0n December 16, 2010 says:
nevermind, i worked it! the way i had incorporated it into my page meant it was double re-directing and the $check value wasn't present on the redirect!

removed the redirect on success of cookie retreval and all is well!

thanks again

N30

Reply
comments n30cr0n December 16, 2010 says:
brilliant script, just what i was looking for! however, i am having a problem with the check box. I have setup the login page with a username and password field, and the checkbox for 'remember me'. for arguments sake i called them all the same as you have.

when it gets to the process script i ger an error stating;

'PHP Notice: Undefined index: setcookie in ../../../..login_auth.php on line 43'

Line 43 is as follows;

$check=$_POST['setcookie'];

the script works and sets the cookie and logs me in but wont forward me back to home page (i have mine setup to do that after login, return to ho

Reply
comments asad August 18, 2010 says:
jnlll.mn,m,.m.
Reply
comments Chasm April 28, 2010 says:
Exactly, Johannes.

In your DB add a "tempToken" field. Now every time the user logs in store an md5(user id + current time + some other salt) in you tempToken field.
When the user comes back, if they have the cookie, lookup your tempToken in the DB and you know who the user is without giving out any information.

An advantage is that if you change the salt on the server, then it will disable all current tempTokens out there and everyone will be forced to re-login again.

Reply
comments Johannes April 14, 2010 says:
Saving username and password is an obvious, but absolutely crappy way to to it. Please: Learn from the article, but don't do it that way. Hashing the password makes things a little better. However you should better use a random token which does not contain user informations.
Reply
Add comments to "Cookies / Remember Me"

Captcha