How to add Remember-Me in login form using PHP session and cookie

The "Remember Me" checkbox in a login form is used to make user login easily as the user does not have to enter userid every time he/she logs in the system. If this checkbox is checked, a login form will automatically remember the userid next time the user logs in. We will use PHP session and cookies in this tutorial.

how to code Remember me in PHP

In this topic, we will develop a PHP login form with "Remember Me" option using PHP and MySQL. If the user selects the checkbox during login, it will remember the email id and will be displayed next time user opens the login form. We will use PHP session and cookies to implement it. Use PHP setcookie() to create a cookie and read the cookie later.


setcookie ("remember_email",$email,time() + 3600*24*365);
setcookie ("remember",$remember,time() + 3600*24*365);

Two cookies will be saved here, one for email id and other for the checkbox.

Next, in the Login form, we will use below code for input email id and "Remember Me" checkbox.


<input type = "text" class="form-control" name="email" id = "email" value= "<?php if(isset($_COOKIE["remember_email"])) { echo $_COOKIE["remember_email"]; } else echo $email;?>" placeholder ="Enter your Email Id" required>

<input type="checkbox" name = "remember" class="check" <?php if(isset($_COOKIE["remember"])) { ?> checked <?php } elseif(!empty($remember)) { ?> checked <?php } ?>>Remember Me

With this, let us develop a login form using email id and password with "Remember Me" option. If the user selects the checkbox, he or she should see the email id automatically displayed, and the checkbox is checked in the next login.

You can also read below topics where step by step description of the topics are available:

  1. How to display user name on header after login using PHP session
  2. How to code Login, Logout and Change Password in PHP and MySQL

Watch YouTube Video

login and logout in php with mysqlFolders and Files

Screenshot of the folder structure and files:

Implement Remember Me in PHP Securely

In 'cfg' folder, we have kept dbconnect.php, it is used to connect to MySQL database.
In 'css' folder Custom stylesheet is written.

index.php is the home page and header.php is the html header layout. The home page is very simple, user can click on Login link and login into the system.

Step 1 - Create a MySQL table to store user details

The table named 'users' is used in MySQL database to store user details. Table structure is given below:

Remember Me for Login using PHP Session and cookie

Table has 5 columns.

  1. id - it is the primary key and auto incremented
  2. email - email id of the user
  3. name - name of the user
  4. password - password for the user
  5. signup_date - date of signup, default is current date, this is not required for login, used as information purpose only
SQL script to create this table is given below:

users.sql


  CREATE TABLE `users` (
    `id` int(11) NOT NULL,
    `email` varchar(255) NOT NULL,
    `name` varchar(255) NOT NULL,
    `password` varchar(255) NOT NULL,
    `signup_date` datetime NOT NULL DEFAULT current_timestamp()
  ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
  
  INSERT INTO `users` (`id`, `email`, `name`, `password`) VALUES
  (1, 'test@test.com', 'Test User', '202cb962ac59075b964b07152d234b70');
  
  --
  ALTER TABLE `users`
    ADD PRIMARY KEY (`id`);
  
  ALTER TABLE `users`
    MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;

After running the above script, below data should be in the table. Just verify that. Password is "123", stored as md5 hash.

Remember me feature on login page using PHP

Step 2 - Connect to MySQL database (dbconnect.php)

PHP script to connect to MySQL database is given below. We have created this under "cfg" folder and will include this in all other programs where database access is needed.

dbconnect.php


$server="localhost";
$userid="root";
$pwd="";
$dbname="demo";
$conn = mysqli_connect($server, $userid, $pwd, $dbname);
//Check connection
if (!$conn) 
  die("Connection Error: " . mysqli_connect_error());

mysqli_connect() function is used here to connect to the database. Our database name is "demo" and we are using "root" user.

You can read the topic How to connect to MySQL database in PHP using MySQLi and PDO for details.

Step 3 - Create a Home Page (index.php)

The Home page is very simple. It has a link for the user to login. You can develop your own home page and add login link in it. header.php is used as below:

header.php


<?php
if (!session_id()) session_start(); ?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0">
<meta name="description" content="">
<title>Remember Me</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<link rel="stylesheet" href="css/style.css">
</head>
<body>

PHP session_start() function is used at the beginning. Below code is for index.php.

index.php


<?php 
include 'header.php';
?>
<h1> My Home Page </h1>
<?php if (isset($_SESSION['email'])) { 
echo "<h2>Welcome ".$_SESSION['name'].". Your email id is ".$_SESSION['email']."</h2>"; 
?>
<h3><a href="logout.php">Logout </a></h3>
<?php } 
else {
	?>
	<h3>Click <a href="login.php">here</a> to login</h3>
<?php } ?>
</body>
</html> 

We are displaying user name and email id when user is logged in. Using PHP session variable, we can check if user is logged in or not. These PHP Session variables are set after successful login which you will see in next step. If the user is not logged in then Login link is displayed.

Step 4 - Develop a Login form (login.php)

We will use email id and password to login to the system. There will be a "Remember Me" checkbox. PHP cookies will be created if "Remember Me" checkbox is checked by the user during login.

Remember me option using PHP Cookie

Let us look at the code when the login form is submitted.


<?php
session_start();
include "cfg/dbconnect.php";
$email = $password = $err_msg = "";
$remember = "";

if (isset($_POST['submit'])) {    // if Form is submitted
	$email = trim($_POST['email']);
	$password = trim($_POST['password']);
	if (isset($_POST['remember'])) {  // if remember me is checked
		$remember = $_POST['remember'];
	}
	$password = md5($password);
	// check if emailid and password are same as stored in the database
	$sql = "select * from users where email = '$email' and password = '$password'";
	$result = mysqli_query($conn,$sql);
	if (mysqli_num_rows($result) > 0) {
		$row = mysqli_fetch_array($result);
		$_SESSION['name'] = $row['name'];
		$_SESSION['email'] = $email;
		if (isset($_POST['remember'])) {  // if remember me is checked
			$remember = $_POST['remember'];
			setcookie ("remember_email",$email,time() + 3600*24*365);
			setcookie ("remember",$remember,time() + 3600*24*365);
			}
		else {
			setcookie("remember_email","", time() - 36000);
			setcookie("remember","", time() - 3600);
			}
		header("location:index.php");
	}
	else 
		$err_msg = "Incorrect Email Id/Password";
}

After the form is submitted and if login is successful, we check if "Remember Me" checkbox is checked by the user in line 21. If checked then create two cookies - one for email id and the other for "Remember Me" checkbox itself. PHP setcookie() function is used to store email id value in a cookie named "remember_email" and this cookie will expire after 365 days, converted to seconds. Similarly, "remember" cookie is set. If the user unchecks the checkbox, we need to remove the cookies. In lines 27 and 28, we are removing these two cookies by setting a past expiration date. Note the minus ("-") sign.

Now, in the login form, we will display email id in the email field and check the checkbox if the corresponding cookies exist. See the code below in the login form:


<form class="form-1" action="login.php" method ="post">
  <h2>Login Form</h2>
      <?php if ($err_msg !="") ?>
  <p class="err-msg"><?php echo $err_msg; $err_msg ="";?></p>
  <div class="col-md-12 form-group">
    <label>Email Id</label>
    <input type = "text" class="form-control" name="email" id = "email" value= "<?php if(!empty($email)) { echo $email; } elseif (isset($_COOKIE["remember_email"])) {echo $_COOKIE["remember_email"];}?>" placeholder ="Enter your Email Id" required>
  </div>>
  <div class="col-md-12 form-group">
    <label>Password</label>
    <input type = "password" class="form-control" name="password" id = "password" placeholder ="Enter Password" required>
  </div>
  <div class="col-md-12 form-group">
    <input type="checkbox" name = "remember" class="check" <?php if(!empty($remember)) { ?> checked <?php } elseif(isset($_COOKIE["remember"])) { ?> checked <?php } ?>>Remember Me
  </div>
  <div class="col-md-12 form-group text-right">
    <button type="submit" class="btn btn-primary" name="submit">Login</button>  
    <a href="index.php" class="btn btn-danger" name="cancel">Cancel</a>
  </div>
</form>

Check the value for email id, if the cookie for the "email" exist, if exists then assign cookie value in the email field. Similarly, for the checkbox, check if the cookie for "remember" exists, if exists, then checkbox is checked.

Now we will add code for logout.php as below:

logout.php


<?php
session_start();
session_unset();
session_destroy();
header("location:index.php");
?>

Here, all session variables are removed using session_unset() and the session is deleted using session_destroy().

Step 5 - Add CSS (style.css)

Let us add below styles. We have already added style.css in header.php.

style.css


* {box-sizing: border-box;
}
h1,h2,h3{
  text-align: center;
  margin-top: 30px;
}
h2{
  color:#1c47a9;
}

.err-msg{
  text-align: center;
  color:red;
}

.form-1 {
  margin: 50px auto;
  padding-bottom: 30px;
  border: 1px solid #09168d;
  border-radius: 7px;
  background: #fff;
  width: 37%;
}
p{
  text-align: center;
}
.check {
  margin:  5px 0px;
  width: 6%;
  height: 20px;
  }
@media  screen and (max-width: 700px) {
  .form-1 {
    width: 80%; 
  }
}
  

Our development is complete, let us test the application.

remember me cookie phpTest the Application

In the browser run localhost/remember_me. You should see the home page. Click on the Login link, you will see Login Page is opened.

In the Login form, enter email id as 'test@test.com', password as '123', check 'Remember Me' checkbox and click on Login button.

After successful login, you should see the Logout link. Click on Logout and then click on Login again. You should see the email is displayed and remember-me checkbox is checked automatically in the login form.

PHP Remember me using Cookie

If you login again with the checkbox unchecked, and logout and click on login again, you will see that email id is not displayed anymore and checkbox is not checked in the login form.

Hope You could understand all the steps and could test it successfully. You can now play around with it and test more with your own test cases.

Watch YouTube Video

download source code Remember me in PHPDownload Source Code

Click on the download button to download the source code. You do not have to signup for this. You can always modify the code to meet your requirements.

create a login system with remember me feature in phpConclusion

In this example I have showed you how you can develop PHP login form with "Remember Me" using PHP session and cookie. This is a basic need for a web application where user login is used. I made it very simple for you, you can always improve it. Hope it will be useful for you.