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

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

login.php:

<?php 
include ("config.php");
include ("logic.php");
?>
<!doctype html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
     <!-- Sweet Alert CDN -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/2.1.2/sweetalert.min.js"></script>
    <title>Bootstrap Login Form</title>
  </head>
  <body>
   <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.
      </div>
    </div>          

    <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
      </div>
    </div> 
    <!-- 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
        </label>                
      </div>
    </div>
    <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>
    </div>
  <span class="extra-line text-center">
    <span>Don't have an account ?</span>
    <a href="register.php">Register</a>
  </span>
</form>
</div>
</div>
</div>
</div>
</div>
    <!-- Optional JavaScript; choose one of the two! -->
    <!-- Option 1: Bootstrap Bundle with Popper -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
    <!-- Option 2: Separate Popper and Bootstrap JS -->
    <!-- <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.2/dist/umd/popper.min.js" integrity="sha384-IQsoLXl5PILFhosVNubq5LC7Qb9DXgDA9i+tQ8Zj3iwWAwPtgFTxbJ8NT4GN1R8p" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.min.js" integrity="sha384-cVKIPhGWiC2Al4u+LWgxfKTRIcfu0JTxR+EQDz/bgldoEyl4H0zUF0QKbrJ0EcQF" crossorigin="anonymous"></script>
    -->
  </body>
</html>

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

config.php:

<?php 
  session_start();
  // 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 -

logic.php:

<?php 
session_start();
/*------------------------------------
// 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
				setcookie('emailcookies',$email,time()+900);
				setcookie('passwordcookies',$password,time()+900);
			}
// redirect to welcome page
				header('location: index.php');				
				exit(0);
	}else{
		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 -

users:


INSERT INTO `users` (`id`, `email`, `password`) VALUES (NULL, 'example@gmail.com', 'password');

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

logout.php:

<?php 
    session_start();
    session_destroy();
    session_unset();
    header('location: index.php');
    setcookie('emailcookies',$email,time()-900);
    setcookie('passwordcookies',$password,time()-900);
?>

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 logs in again. In this way, our How to Add Remember Me Functionality in the Login Page using PHP ends.

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

Demo of Remember Me functionality


Conclusion:

Today we learned about How to Add Remember Me Functionality in the 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 👉 example@gmail.com

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

0 Comments