How to Create a PHP AutoLogin (‘Remember Me’) Feature using Cookies
Posted on November 25, 2008, Filled under PHP,
Bookmark it
Thanks for visiting our website! We regularly publish posts like this one. If you are interested in receiving the latest updates as soon as they are posted, please consider subscribing to the RSS feed or to our e-mail newsletter.
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> </label><input type="checkbox" name="autologin" value="1">Remember Me<br />
<label> </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


Do you wish to receive the latest updates as soon as they are posted? Get our RSS Feed or Subscribe to the Newsletter!
- November 25, 2008
- article by Gabriel C.
- 9 comments
Sponsors
Related Posts
-
Create a PHP Script that Logins in to a Password Protected Areaat December 17, 2008 with 14 comments
-
Basic PHP Captcha (Image Verification) with Refresh Featureat February 10, 2009 with 14 comments
-
PHP: Practical cURL functionat September 2, 2008 with 1 comment
-
PHP: Sanitize Data to Prevent SQL Injection Attacksat January 9, 2009 with 6 comments
-
Creating an AJAX Login Form using MooToolsat December 21, 2008 with 26 comments


9 Replies to "How to Create a PHP AutoLogin (‘Remember Me’) Feature using Cookies"
November 26, 2008 at 9:12 AM
form.php:12
isset() already returns a boolean
Also, it would be a good idea to add a salt to the hash.
November 29, 2008 at 9:02 AM
Never do it:
if(@$_COOKIE[$cookie_name])
It should be corrected to
if (isset($_COOKIE[$cookie_name]))
December 12, 2008 at 11:43 PM
[...] view plaincopy to [...]
February 7, 2009 at 4:37 AM
i want to many member login in this application? how to add members
# // ———- Login Info ———- //
#
# $config_username = 'user';
# $config_password = 'demo123';
March 24, 2009 at 5:35 PM
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 ???
July 25, 2009 at 9:15 PM
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.
September 4, 2009 at 3:34 PM
Wow!!! Gr8 code n it really works…..It helpz me a lot…
October 15, 2009 at 10:06 PM
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
October 15, 2009 at 10:18 PM
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