PHP Login Form with Remember-Me using Cookie and Session

The "Remember Me" checkbox in a login form can be implemented using PHP cookies. If this checkbox is checked, the login form will automatically remember the userid during the next login. In this tutorial, we will use PHP session and cookies in a PHP login form.

how to code Remember me in PHP using cookie

We will develop a PHP login form with "Remember Me" checkbox 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. 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, one for the email id and the other for the checkbox.

Next, in the Login form, we will use the below code for the 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 an email id and password with the "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 the below topics where step-by-step development details are available:

  1. 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 mysql and cookieFolders and Files

Screenshot of the folder structure and files:

Implement Remember Me in PHP login form

In the 'cfg' folder, we have kept dbconnect.php, it is used to connect to the MySQL database.
The 'css' folder is for our custom stylesheet.

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

Create a MySQL table to store user details

We will use a table named 'users' in the MySQL database to store the user details. The table structure is given below:

Remember Me for Login using PHP Session and cookie

The 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;

Connect to MySQL database (dbconnect.php)

The PHP code to connect to the MySQL database is given below. We have created this under the "cfg" folder and will include this in all other programs required to access the database.

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 will use the "root" user.

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

Create a Home Page (index.php)

The Home page is a simple web page here. It has a link for the user to login. You can develop your home page and add a login link to 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. The 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 display the user's name and email id when the user is logged in. Using the PHP session variable, we can check if a user is logged in or not. These PHP Session variables are set after successful login which you will see in the next section. If the user is not logged in then the Login link is displayed.

Develop a Login form (login.php)

We will use an email id and password to login into the system. We will create a PHP login Remember Me cookie if the "Remember Me" checkbox is checked by the user during login.

Remember me option using PHP Cookie

Let us look at the PHP code for login page after the 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 the "Remember Me" checkbox is checked by the user in line 21. If checked then create two cookies - one for the email id and the other for the "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, the cookie named "remember" 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 the email id in the email field and check the checkbox if the corresponding cookies exist. See the below code 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 the email id if the cookie for the "email" exists. If exists then assign the cookie value in the email field. Similarly, for the checkbox, check if the cookie for "remember" exists, if exists, then the 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().

Add CSS (style.css)

Let us add the 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 the Login Page is displayed.

In the Login form, enter the email id as 'test@test.com', password as '123', check the 'Remember Me' checkbox and click on the 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 the "Remember Me" checkbox is checked automatically in the login form.

PHP Remember me using Cookie

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

download source code Remember me in PHPDownload Source Code

Click on the download button to download the source code. You do not have to sign up 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 shown how you can develop a 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 simple for you. You can always improve it. I hope it will be useful to you.

Post a Comment

Save my Name and Email id for future comments