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:


require_once 'config.php';

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

header("Location: private.php");

$do_login = true;

include_once 'do_login.php';
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
  <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">
padding: 0;border: 0px none;

/* Stylish 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 */
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; }

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

/* BR */

br { clear: left; }




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


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 />





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:


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 ---------- //

include_once 'autologin.php';


	// Check if the cookie exists

	// 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:


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");
$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).

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: You will see that you’re automatically logged in without needing to enter the username & password again 😉

Comment via Facebook



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

  2. says

    Log out is not working:

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

    seems incomplete, it does not remove the cookie siteAuth

  3. Sebastian Grignoli says

    Use this:

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

    instead of this:


    and this:

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

    instead of this:

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

  4. Sebastian Grignoli says

    At least use this:

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

    instead of this:


    and this:

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

    instead of this:

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

  5. Gabriel C.Gabriel C. says

    @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.

  6. afif ahmad hidayat says

    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.

  7. Sebastian Grignoli says

    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.

  8. afif ahmad says

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

  9. Sebastian Grignoli says

    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.

    • Gabriel C.Gabriel C. says

      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.

  10. chennaizoom says

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

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

  11. Kevin says

    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?


  12. Sarah says


    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. Nile says

    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…

  14. Stonedeft says


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


    • Gabriel C.Gabriel C. says

      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:

  15. johan says

    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.


  16. johan says

    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

  17. says

    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.

  18. Jörg says

    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 ???

  19. Sami says

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

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


Leave a Reply

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