Creating a Login Remember Me Feature in PHP Tutorial

Introduction

In this tutorial, you will learn how to Create a Login Form Remember Me Feature using PHP Language. The tutorial aims to provide the students and new programmers a reference to learn with and enhance their programming capabilities using the PHP Language. To achieve this kind of feature we will be using the HTTP Cookies. Here, snippets and sample source code are provided for a better understanding about the process.

What is HTTP Cookie?

HTTP Cookie is small blocks of data sent by the web server to the user's computer or device browsers. It is consist of name and value. In PHP,  cookie is a tiny file that the web server stores on the client computer. They are often used to store data, like a username, that the website can access later to customize the user's experience when they visit the site again. Only the domain from which it was issued may read cookies.

How to use HTTP Cookie in PHP?

The syntax of setting a cookie using PHP si very simple. See the following snippet for setting an cookie in PHP.

  1. <?php
  2. setcookie(name, value, expiration, path, domain, Secure);
  3. //or
  4. setcookie(name, value, [options])
  5. ?>

Syntax Parameters:

  • Name - (string) the name of the cookie.
  • Value - (string) the value of the cookie.
  • Expiration - (timestamp) the expiration timestamp of the cookie.
  • Path - (string) the path in which the cookie will be available
  • Domain - (string) the domain in which the cookie will be available
  • Secure - (boolean) if set to true, the cookie will be only set if the connection is secure.
  • HTTP Only - (boolean) if set to true, the cookie will be only accessible through HTTP protocol.

How to Create a Login Form Remember Me Feature in PHP?

Creating a login form with the "Remember Me" feature can be achieved using the HTTP Cookie. Using a checkbox on the login form, a developer can let the user decide whether the browser should remember their input credential for logging in or not. If the user marked it checked, the server will store the credentials data of the user to the browser using PHP Cookie. Here's an example snippet for doing it on the server side:

  1. <?php
  2. /**
  3. * Saving the input data to Cookie
  4. */
  5. if(isset($_POST['rememberMe'])){
  6. /**
  7.   * Store Login Credential
  8.   */
  9. setcookie('username', $_POST['username'], ( time() + ((365 * 24 * 60 * 60) *3) ));
  10. setcookie('password', $_POST['password'], ( time() + ((365 * 24 * 60 * 60) *3) ));
  11. }else{
  12. /**
  13.   * Delete Login Credential
  14.   */
  15. setcookie('username', $_POST['username'], ( time() - (24 * 60 * 60) ));
  16. setcookie('password', $_POST['password'], ( time() - (24 * 60 * 60) ));
  17. }

The snippet above demonstrates that the cookies will be only stored if the "Remember Me" checkbox is checked otherwise it will be removed after the login process.

Example

Here's a sample web application that demonstrates the Login Form with Remember Me Feature in PHP Language. The application is a simple login system that allows the end-user to decide if they want to store their credential in the browser so they won't need to type them if they log in again in the future.

Database Schema

Create a new Database in your MySQL Server and use the following schema for the sample user table.

  1. CREATE TABLE `users` (
  2. `name` varchar(250) NOT NULL,
  3. `username` varchar(50) NOT NULL,
  4. `password` text NOT NULL

Authentication Script

In your source code folder create a new PHP Script that will check if the user is already authenticated.

auth.php

  1. <?php
  2. if(strstr($_SERVER['PHP_SELF'], "index.php") === false){
  3. if(!isset($_SESSION['login_id'])){
  4. header("location: ./");
  5. }
  6. }
  7. if(strstr($_SERVER['PHP_SELF'], "welcome.php") === false){
  8. if(isset($_SESSION['login_id'])){
  9. header("location: ./welcome.php");
  10. }
  11. }
  12. ?>

Login Page Interface

Creating the Login Page interface. The authentication script is included with this script.

index.php

  1. <?php require_once("auth.php"); ?>
  2. <!DOCTYPE html>
  3. <html lang="en">
  4. <meta charset="UTF-8">
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7. <title>PHP - Login with Remember Me</title>
  8.  
  9. <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous">
  10. <script src="https://code.jquery.com/jquery-3.6.1.min.js" integrity="sha256-o88AwQnZB+VDvE9tvIXrMQaPlFFSUTR+nldQm1LuPXQ=" crossorigin="anonymous"></script>
  11. <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-OERcA2EqjJCMA+/3y+gxIOqMEjwtxJY7qPCqsdltbNJuaOe923+mo//f6V8Qbsw3" crossorigin="anonymous"></script>
  12. html, body{
  13. min-height:100%;
  14. width:100%;
  15. }
  16. </style>
  17. </head>
  18. <nav class="navbar navbar-expand-lg navbar-dark bg-primary bg-gradient">
  19. <div class="container">
  20. <a class="navbar-brand" href="./">PHP - Login with Remember Me</a>
  21. <div>
  22. <a href="https://sourcecodester.com" class="text-light fw-bolder h6 text-decoration-none" target="_blank">SourceCodester</a>
  23. </div>
  24. </div>
  25. </nav>
  26. <div class="container-fluid px-5 my-3 h-75">
  27. <div class="col-lg-4 col-md-5 col-sm-12 mx-auto my-5 pt-5" >
  28. <div class="card rounded-0 shadow">
  29. <div class="card-header">
  30. <h3 class="card-title text-center fw-bold">Login</h3>
  31. </div>
  32. <div class="card-body">
  33. <div class="container-fluid">
  34. <form id="loginForm" action="login.php" method="POST">
  35. <div class="mb-3">
  36. <label for="username" class="form-label">Username</label>
  37. <input type="text" class="form-control form-control-sm rounded-0" name="username" id="username" value="<?= isset($_COOKIE['username']) ? $_COOKIE['username'] : '' ?>" required autocomplete="off">
  38. </div>
  39. <div class="mb-3">
  40. <label for="password" class="form-label">Password</label>
  41. <input type="password" class="form-control form-control-sm rounded-0" name="password" id="password" value="<?= isset($_COOKIE['password']) ? $_COOKIE['password'] : '' ?>" required autocomplete="off">
  42. </div>
  43. <div class="mb-3">
  44. <div class="form-check">
  45. <input class="form-check-input" type="checkbox" value="" id="rememberMe" name="rememberMe" <?= (isset($_COOKIE['username']) && isset($_COOKIE['password'])) ? "checked" : '' ?>>
  46. <label class="form-check-label" for="rememberMe">
  47. Remember Me
  48. </label>
  49. </div>
  50. </div>
  51. </form>
  52. </div>
  53. </div>
  54. <div class="card-footer py-2">
  55. <div class="text-center">
  56. <button class="btn btn-sm btn-primary rounded-pill col-lg-4 col-md-6 col-sm-12" form="loginForm">Login</button>
  57. </div>
  58. </div>
  59. </div>
  60. </div>
  61. </div>
  62. </body>
  63. </html>

Login Script

The snippet below is the PHP Script that processes the given login credential of the users. It stores the credential data as Cookie if the "Remember Me" checkbox is checked and the credentials are valid.

login.php

  1. <?php
  2.  
  3. $conn = new mysqli("localhost", "root", "", "dummy_db");
  4. if(!$conn)
  5. die("Database Connection Failed");
  6. $username = addslashes($conn->real_escape_string($_POST['username']));
  7. $password = md5($conn->real_escape_string($_POST['password']));
  8.  
  9. $stmt = $conn->prepare("SELECT * FROM `users` where `username` = ? and `password` = ?");
  10. $stmt->bind_param('ss', $username, $password);
  11. $stmt->execute();
  12. $result = $stmt->get_result();
  13. if($result->num_rows > 0){
  14. $data = $result->fetch_assoc();
  15. foreach($data as $k => $v){
  16. $_SESSION['login_'.$k] = $v;
  17. }
  18. /**
  19.   * Saving the input data to Cookie
  20.   */
  21. if(isset($_POST['rememberMe'])){
  22. /**
  23.   * Store Login Credential
  24.   */
  25. setcookie('username', $_POST['username'], ( time() + ((365 * 24 * 60 * 60) *3) ));
  26. setcookie('password', $_POST['password'], ( time() + ((365 * 24 * 60 * 60) *3) ));
  27. }else{
  28. /**
  29.   * Delete Login Credential
  30.   */
  31. setcookie('username', $_POST['username'], ( time() - (24 * 60 * 60) ));
  32. setcookie('password', $_POST['password'], ( time() - (24 * 60 * 60) ));
  33. }
  34. echo "<script>location.replace('./welcome.php')</script>";
  35. }else{
  36. echo "<script>alert('Username and Password does not match.'); location.replace('./')</script>";
  37. }
  38.  
  39. ?>

Home Page Interface

Here's the script for the sample site's home page where the user will be redirected after successful login.

welcome.php

  1. <?php require_once("auth.php"); ?>
  2. <!DOCTYPE html>
  3. <html lang="en">
  4. <head>
  5. <meta charset="UTF-8">
  6. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  7. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  8. <title>Home | PHP - Login with Remember Me</title>
  9.  
  10. <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous">
  11. <script src="https://code.jquery.com/jquery-3.6.1.min.js" integrity="sha256-o88AwQnZB+VDvE9tvIXrMQaPlFFSUTR+nldQm1LuPXQ=" crossorigin="anonymous"></script>
  12. <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-OERcA2EqjJCMA+/3y+gxIOqMEjwtxJY7qPCqsdltbNJuaOe923+mo//f6V8Qbsw3" crossorigin="anonymous"></script>
  13. html, body{
  14. min-height:100%;
  15. width:100%;
  16. }
  17. </style>
  18. </head>
  19. <body>
  20. <nav class="navbar navbar-expand-lg navbar-dark bg-primary bg-gradient">
  21. <div class="container">
  22. <a class="navbar-brand" href="./">PHP - Login with Remember Me</a>
  23. <div>
  24. <a href="https://sourcecodester.com" class="text-light fw-bolder h6 text-decoration-none" target="_blank">SourceCodester</a>
  25. </div>
  26. </div>
  27. </nav>
  28. <div class="container-fluid px-5 my-3 h-75">
  29. <div class="col-lg-4 col-md-5 col-sm-12 mx-auto my-5 pt-5" >
  30. <div class="card rounded-0 shadow">
  31. <div class="card-header">
  32. <h3 class="card-title text-center fw-bold">Welcome</h3>
  33. </div>
  34. <div class="card-body">
  35. <div class="container-fluid">
  36. <h2>You are logged in.</h2>
  37. <dl>
  38. <dt>Name:</dt>
  39. <dd><?= $_SESSION['login_name'] ?></dd>
  40. <dt>Username:</dt>
  41. <dd><?= $_SESSION['login_username'] ?></dd>
  42. </dl>
  43. </div>
  44. </div>
  45. <div class="card-footer py-2">
  46. <div class="text-center">
  47. <a class="btn btn-sm btn-danger rounded-pill col-lg-4 col-md-6 col-sm-12" href="logout.php">Logout</a>
  48. </div>
  49. </div>
  50. </div>
  51. </div>
  52. </div>
  53. </body>
  54. </html>

Logout Script

Here's the script for logging out.

logout.php

  1. <?php
  2. header('location: ./');

Snapshot

Here's a sample snapshot of the login page of the example web application I provided using the source code above.

Login Form with Remeber Me Feature in PHP

DEMO VIDEO

The complete source code zip file of the example source code is also provided on this site. It is free to download. The download link can be found below this article.

That's the end of this tutorial! I hope this Login Form with Remember Me Feature Tutorial in PHP will help you with what you are looking for and that you'll find it useful for your current and future PHP Projects.

Explore more on this website for more Tutorials and Free Source Codes.

Happy Coding :)

Add new comment