How to Create a PHP AutoLogin (‘Remember Me’) Feature using Cookies

This tutorial will give you an idea of how you can implement an auto-login feature in PHP. Many sites have this option and I use it a lot when I have the chance because there are sites that I visit daily and it would be frustrating for me to type my username and password every time I have to log in. However, there are some things that you should take into consideration before using this option.

To make such a feature we have to use a cookie. You have to make sure that you DO NOT use this option when you’re working on a public computer (example: one from an Internet Cafe). This way, no one that will use the same computer will get access to your account(s) (for example: your Inbox from GMail). There’s also one important aspect: make sure that the saved cookies are not containing your password. Usually you should see a long encrypted string. Sites that do not respect this ‘rule’ shouldn’t be trusted.

Let’s begin with the creation of the sample tableless login form:

form.php

<?php
require_once 'config.php';

// Is the user already logged in? Redirect him/her to the private page

if($_SESSION['username'])
{
header("Location: private.php");
exit;
}

if(isSet($_POST['submit']))
{
$do_login = true;

include_once 'do_login.php';
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
 <HEAD>
  <TITLE>TableLess Login Form</TITLE>

  <META name="Author" Content="Bit Repository">
  <META name="Keywords" Content="form, divs">
  <META name="Description" Content="A CSS Tableless Form Design">

<STYLE TYPE="text/css">
<!--
HTML, BODY
{
padding: 0;border: 0px none;
}

/* Stylish FieldSet */
fieldset
{
-moz-border-radius: 7px; border: 1px #dddddd solid; padding: 10px; width: 330px; margin-top: 10px;
}

fieldset legend
{
border: 1px #1a6f93 solid; color: black; font: 13px Verdana; padding: 2 5 2 5; -moz-border-radius: 3px;
}

/* Label */
label
{
width: 100px; padding-left: 20px; margin: 5px; float: left; text-align: left;
}

/* Input text */
input { margin: 5px; padding: 0px; float: left; }

/* 'Login' Button */
#submit { margin: 5px; padding: 0px; float: left; width: 50px; background-color: white; }

#error_notification
{
border: 1px #A25965 solid;
height: auto;
padding: 4px;
background: #F8F0F1;
text-align: center;
-moz-border-radius: 5px;
}

/* BR */

br { clear: left; }
-->
</STYLE>

</HEAD>

 <BODY>

<center>

<div align="left" style="width: 330px;">
<form name="login" method="post" action="login.php">

<fieldset><legend>Authentication</legend>

<?php
if($login_error)
{
echo '<div id="error_notification">The submitted login info is incorrect.</div>';
}
?>

<label>Username</label><input id="name" type="text" name="username"><br />

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

<label>&nbsp;</label><input type="checkbox" name="autologin" value="1">Remember Me<br />

<label>&nbsp;</label><input id="submit" type="submit" name="submit" value="Login"><br />

</fieldset>

</form>
</div>

</center>

 </BODY>
</HTML>

Both the login info and the session data initialization are stored in config.php. In this file, we also have some cookie variables ($session_name & $session_time) and the auto-login checker:

config.php

<?php
error_reporting(E_ALL ^ E_NOTICE);

session_start(); // Start Session
header('Cache-control: private'); // IE 6 FIX

// always modified
header('Last-Modified: ' . gmdate("D, d M Y H:i:s") . ' GMT');
// HTTP/1.1
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
// HTTP/1.0
header('Pragma: no-cache');

// ---------- Login Info ---------- //

$config_username = 'user';
$config_password = 'demo123';

// ---------- Cookie Info ---------- //

$cookie_name = 'siteAuth';
$cookie_time = (3600 * 24 * 30); // 30 days

// ---------- Invoke Auto-Login if no session is registered ---------- //

if(!$_SESSION['username'])
{
include_once 'autologin.php';
}
?>

autologin.php

<?php
if(isSet($cookie_name))
{
	// Check if the cookie exists
if(isSet($_COOKIE[$cookie_name]))
	{
	parse_str($_COOKIE[$cookie_name]);

	// Make a verification

	if(($usr == $config_username) && ($hash == md5($config_password)))
		{
		// Register the session
		$_SESSION['username'] = $config_username;
		}
	}
}
?>

The name of the auto-login cookie is “siteAuth” and it’s kept in the user’s computer for 30 days. This means that the site’s member can use the auto-login for the following month. After the cookie expires, the user will have to re-login. If he chooses to sign out, by pressing the “Logout” link from his private page both the registered session (‘username’) and the cookie (‘siteAuth’) will be erased.

Here’s the script that checks if the login info is valid or not:

do_login.php

<?php
if(!$do_login) exit;

// declare post fields

$post_username = trim($_POST['username']);
$post_password = trim($_POST['password']);

$post_autologin = $_POST['autologin'];

if(($post_username == $config_username) && ($post_password == $config_password))
{
$login_ok = true;

$_SESSION['username'] = $config_username;

// Autologin Requested?

if($post_autologin == 1)
	{
	$password_hash = md5($config_password); // will result in a 32 characters hash

	setcookie ($cookie_name, 'usr='.$config_username.'&hash='.$password_hash, time() + $cookie_time);
	}

header("Location: private.php");
exit;
}
else
{
$login_error = true;
}
?>

If the login info is correct, the user is logged in, by registering the session ‘username’ & a cookie is set in his computer if he checked the “Remember Me” checkbox. The cookie will contain the username and a 32 character hash which is the md5 equivalent of the password (example: usr=user&hash=d41d8cd98f00b204e9800998ecf8427e).

DEMO
Use the following credentials:
Username: user
Password: demo123

Make sure you check the “Remember Me” checkbox before submitting the form. After you successfully login, close the browser window and reopen it. Use the following address to go to the private page: http://www.bitrepository.com/demo/autologin/private.php. You will see that you’re automatically logged in without needing to enter the username & password again ;-)

Comment via Facebook

comments

30 Comments

  1. Sebastian Grignoli says

    Use this:

    parse_str($_COOKIE[$cookie_name], $received);

    instead of this:

    parse_str($_COOKIE[$cookie_name]);

    and this:

    if($received["usr"] == $config_username && $received["hash"] == md5($config_password))

    instead of this:

    if(($usr == $config_username) && ($hash == md5($config_password)))

  2. says

    Log out is not working:

    setcookie ($cookie_name, ”, time() – $cookie_time);

    seems incomplete, it does not remove the cookie siteAuth

  3. Mat says

    This solution is absolutely not secure because md5 could be brokn easily. Moreover, you should not store password in cookie, even if it is encrypted…

Trackbacks

Leave a Reply

Your email address will not be published. Required fields are marked *