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

Posted on November 25, 2008, under PHP 

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

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

  1. form.php:12
    isset() already returns a boolean

    Also, it would be a good idea to add a salt to the hash.

  2. Never do it:

    if(@$_COOKIE[$cookie_name])

    It should be corrected to

    if (isset($_COOKIE[$cookie_name]))

  3. i want to many member login in this application? how to add members

    # // ———- Login Info ———- //
    #
    # $config_username = 'user';
    # $config_password = 'demo123';

  4. Hi great Tut!
    One Question. How can i manipulate the name of the Cookie, which appear on the harddisk on the Computer. On my harddisk (WinXP) there ist always the name ‘autologin/’, but i cannot find any Name like this in the files. There ist the var cookie_name = ‘siteAuth’, so i thought the file also has to be named like siteAuth, but is not ???

  5. Great article, I added a salt to the hash and modified this to work with mysql which I was already using the password function. Thanks much.

  6. Wow!!! Gr8 code n it really works…..It helpz me a lot…

  7. how to add multiple users in mysql.
    do i have to put the verification against db in config.php ?

    email me if you read this.thx

  8. how do i add multiple users and connect it to mysql.

    do i have to put the verification against db in config.php ?

    please help me…
    email me if you read this.

    thx

  9. Nice script, was really helpfull :)

  10. Hello

    is trim(); secure enough to against sql injection or do I need to stripslashes() and mysql_real_escape_string() it?

    Tnx

    1. The trim() function just strips the whitespace from the beginning and end of the string. So, you need to use stripslashes() (if magic quotes are turned on) and mysql_real_escape_string() to have protection. Consider checking the following URL: http://bit.ly/1ZN41n

  11. Can’t this result in easy viewing of private.php? What if some one were to set the session username his or herself, instant access to private.php…

  12. Hi,

    How do I sign the user in automatically and also store the cookie on the computer? I am creating a flash site and once the user has watched 2 min animation they will see a button that says click here to enter secret site. They click it and automatically logged into the site. if they try and send the url out to friends they will be unable to log in as they also need to click the button from the flash file

  13. Hi, great script, it’s working perfectly for me and I’m a complete rookie. I was just wondering, how do I allow for multiple username and passwords. For example, if I had two different users who each had a unique username and password?

    Thank!

  14. setcookie ($cookie_name, ‘usr=’.$config_username.’&hash=’.$password_hash, time() + $cookie_time);

    setcookie failed.
    Warning: Cannot modify header information – headers already sent by ….

  15. It would be a good idea to store the cookie encrypted, so network sniffers won´t obtain the username or the password hash.

    Also, parse_str without a second argument is dangerous. It’s in fact a vulnerability.

    The user can tamper with the cookie data and set a value to $config_username and $config_password using that.

    He could force the IF condition to return always true and log in as a different user using any password.

    1. This tutorial was written a long time ago and I just forgot to include config.php in autologin.php. I believe it’s obvious for any PHP developer. I agree that a salt should be added into the the cookie value.

  16. :D That’s ridiculous way. What about edit cookie with firefox?? So I can login without password :D

  17. Afif is right, this method is a complete vulnerability in itself.

    First of all, the cookie will never change, so if someone steals it, it’s just as stealing the password. And believe me, it’s VERY easy to steal over the network.

    Secondly, if I know how this works I could just set the values of $config_username and $config_password (autologin.php, line 07 allows me to do that) to match the user I want to log as, and the password to match the hash I am sending, so the verification would return true and let me in.

    That way I will be logged as any user I want, without knowing the real password.

  18. mayne this is better way: fill cookie with session id is better way. then, in the next request if cookie of remember is exists, set session id with that cookie.

  19. @Afif, @Sebastian I will soon update this post. It will include a better way to store and read the cookie in a secure way. Thank you for all your suggestions. I have to admit that I’ve written this post a long time ago and I missed some key things. I was focusing more of how the “Remember Me” feature can be accomplished and less on its security breaches. Thanks again and my apologies for the inconveniences caused to the readers.

  20. At least 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)))

  21. 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)))

  22. Log out is not working:

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

    seems incomplete, it does not remove the cookie siteAuth

  23. 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…

  24. i want to get my user form my database can you give me code of these requirement

  25. It’s not working with session. How do we working with session cookies

Leave a Reply


* = required fields

  (will not be published)


XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Note: If you want to post CODE Snippets, please make them postable first!
(e.g. <br /> should be converted to &lt;br /&gt;)

POSTING RULES:

  • The comment must be relevant with the topic of the post.
  • Only comments with real email addresses will get approved. So, emails like 'abc@domain.com' will not be accepted.
  • Do not post the same message in multiple articles through the site.
  • Do not post advertisements, junk mail or pyramid schemes.
  • In case you post a link to another site, please explain briefly where the link goes as a courtesy to other users.
  • Do not post comments such as: "Thank you", "Awesome", "Nice tutorial", "Merci", etc.