How to Add Remember Me Functionality in Login Page using PHP

In this tutorial, we will use how to add remember me functionality in the login page using PHP Cookies and Session. In the previous post we saw Registration and Login System in PHP and Mysqli, if you haven't read this post yet, please read that post first, after that we will move on.

So let's start without any delay. Before we begin, let's get to know a little bit about it and how does the Remember Me function work?

How does the Remember Me Function work?

We can call the remember me function, the function of remembering the user's data, it is mostly used in login form authentication. The variable you define in this function stores the data of that variable in the browser's memory. 

For Example -

username/email/password, etc. and it stores the data in the browser until you manually delete it from the browser's cookies and cache memory.

Ok fine, now let's start 👇

you will know that in the previous tutorial we made responsive registration and login form with the help of bootstrap, if you want, you can use it, otherwise, ignore it and go ahead.

First of all, let's create a login form using the help of bootstrap and put the code in the login.php file.


include ("config.php");
include ("logic.php");
<!doctype html>
<html lang="en">
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- Bootstrap CSS -->
    <link href="" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
     <!-- Sweet Alert CDN -->
    <script src=""></script>
    <title>Bootstrap Login Form</title>
   <div class="container-fluid">
<div class="row justify-content-center">
	<div class="col-lg-4 mt-5">
		<div class="card bg-dark text-light">
<h2 class="card-title text-light mt-3" align="center">Login</h2>
<p class="card-text" align="center"> Please Login if you want Access our Webiste</p>
<hr class=" border position-relative " style="width: 70%; align-self: center; margin: 0px;">
<div class="card-body">
<form class="row g-3 mt-0 needs-validation" action="login.php" method="post" novalidate>

    <label for="enteremail" class="form-label">Email</label>
    <div class="input-group has-validation">                          
      <input type="email" class="form-control rounded-pill" name="email" value="<?php if (isset($_COOKIE['emailcookies'])) { echo $_COOKIE['emailcookies'];}?>" id="enteremail"  aria-describedby="inputGroupPrepend" required />
      <div class="invalid-feedback">
        Please Enter Valid Email.

    <label for="password1" class="form-label">Password</label>
    <div class="input-group has-validation">                          
      <input type="password" class="form-control rounded-pill" name="password" value="<?php if (isset($_COOKIE['passwordcookies'])) { echo $_COOKIE['passwordcookies']; } ?>" id="password1" aria-describedby="inputGroupPrepend" required />
      <div class="invalid-feedback">
        Enter Password
    <!-- Remember Me Checkbox -->
    <div class="col-6">
      <div class="form-check">
        <input class="form-check-input" name="remeberme" type="checkbox" value="" id="invalidCheck">
        <label class="form-check-label" for="invalidCheck">
          Remember Me
    <div class="col-md-12 text-center ">
      <button class="btn btn-secondary" name="log_user" title="Submit Your Form" aria-label="Left Align" type="submit"> <span class="fa fa-user" aria-hidden="true"></span> Login</button>
  <span class="extra-line text-center">
    <span>Don't have an account ?</span>
    <a href="register.php">Register</a>
    <!-- Optional JavaScript; choose one of the two! -->
    <!-- Option 1: Bootstrap Bundle with Popper -->
    <script src="" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
    <!-- Option 2: Separate Popper and Bootstrap JS -->
    <!-- <script src="" integrity="sha384-IQsoLXl5PILFhosVNubq5LC7Qb9DXgDA9i+tQ8Zj3iwWAwPtgFTxbJ8NT4GN1R8p" crossorigin="anonymous"></script>
    <script src="" integrity="sha384-cVKIPhGWiC2Al4u+LWgxfKTRIcfu0JTxR+EQDz/bgldoEyl4H0zUF0QKbrJ0EcQF" crossorigin="anonymous"></script>

We haven't done much on the login form page, PHP cookies are set in the value attribute inside the input tag for email and password, a checkbox for the remember me function.

Design the Database for the login form:

Here there is no need for the database, by using the login form, the user's email and password will be stored, and with the help of that, we will complete our work.

By the way, in the previous tutorial, we created a database for the login form. So let's create a database named remember-me and create a table inside it with the name of users.

You can create these tables using these SQL commands.

CREATE TABLE `remember-me`.`users` (`id` INT(11) NOT NULL AUTO_INCREMENT , `email` VARCHAR(100) NOT NULL , `password` VARCHAR(100) NOT NULL , PRIMARY KEY (`id`)) ENGINE = InnoDB;

If you chose to manually create these tables instead, remember to make the id field on the users table a primary key and auto increment.

In config.php, let's add code to connect our application to the database. After adding the code, our config.php file will look like this:


  // connect to database
  $conn = mysqli_connect("localhost", "root", "", "remember-me");
  if (!$conn) {
  die("Error connecting to database: " . mysqli_connect_error());

Now create a file named logic.php. This file is going to hold the logic of our login form, under this we will keep all our PHP logic.

Let's create it in our root folder and put this code inside it -


// Login Users (login.php)

if (isset($_POST['log_user'])) {
	$email = mysqli_real_escape_string($conn, $_POST['email']);
	$password = mysqli_real_escape_string($conn, $_POST['password']);
	if (empty($email)) {
		array_push($errors, "email can not be blank");

// Check Email/Username exists Or no
	$search_email = "SELECT * FROM users WHERE email = '$email' AND password = '$password'";
	$run_query = mysqli_query($conn, $search_email);
	$emailcount = mysqli_num_rows($run_query);

	if ($emailcount) {

		$email_pass = mysqli_fetch_assoc($run_query);
		$db_pass = $email_pass['password'];
		$reg_user_id = $email_pass['id'];
		$_SESSION['user'] = $email_pass['username'];
// put logged in user into session array
			echo '<script type="text/javascript">';
			echo 'setTimeout(function () { swal("Login Successsfully!"," you will redirect Dashboard Page","success");';
			echo '}, 100);</script>';
// Check user click or not click Remember me Checkbox Button
			if (isset($_POST['remeberme'])) { //if user click or checked checkbox then set cookies
// redirect to welcome page
				header('location: index.php');				
		echo '<script type="text/javascript">';
		echo 'setTimeout(function () { swal("Warning!","Email not found","warning");';
		echo '}, 100);</script>';				

Add some records to your database using this SQL command -


INSERT INTO `users` (`id`, `email`, `password`) VALUES (NULL, '', 'password');

Now let's create logout.php file and put this code inside. this logout page destroys the session and cookies.


    header('location: index.php');

In logout, we have destroyed the session and unset where we set the session now if the user is logged out once then he cannot log in until he login again. In this way, our How to Add Remember Me Functionality in Login Page using PHP ends.

Now go to http://localhost/regiter-form/login.php and see the magic.

Demo of Remember me functionality


Today we learned about How to Add Remember Me Functionality in Login Page using PHP. Sorry for this article being long. Hope this article has been very useful for you. If you liked this article then do not forget to like and subscribe to our newsletter and not forget to share it with your friends.

Use this username and password for the demo

Username 👉

Password 👉 password

In the next tutorial, we will see 👉 How to add forgot/reset/recovery passwords using PHP and MYSQL. if any questions related to this article please tell us in the comment box.

Post a Comment