Remember Me Functionality while login using PHP.

Prerequisite: Basic Understanding of HTML, CSS, PHP and MySQL.

In this project:

  • We will create a simple HTML Login Form alongwith a Remember Me button.                                                                                                                          
  • When user will fill the credentials and will also select the Remember Me checkbox cookies will be set which will help user to login again without entering the password everytime.                                                                             
  • Cookie is set for a particular time period and has an expiration time.

Remember Me feature is used to allow the users to save the login details for some particular time period. Cookie is used to set these details. Thing to remember is cookies have an expiration date but they work even after closing web browsers as well.


index.php ⬇

<?php
    @session_start();
    if(isset($_SESSION['user_id']) && is_numeric($_SESSION['user_id'])){
        header("Location:welcome.php");
    }
?>
<!DOCTYPE html>
<html>
    <head>
        <title>LOGIN</title>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
        <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
        <style>
            .row{margin-top: 10px}
            .login_container h4{text-align: center}
            .login_container{background-color: #eeeeee; box-shadow: 10px 10px 10px #ccc; padding: 20px; width: 400px; margin-top: 10%}
            .error{color: red}
        </style>
    </head>
    <body>
        <div class="container login_container">
            <div class="row">
                <div class="col-md-12">
                    <?php
                        if(isset($_SESSION['msg']) && $_SESSION['msg'] != ''){
                            echo "<p class='error'>".$_SESSION['msg']."</p>";
                            unset($_SESSION['msg']);
                        }
                    ?>
                </div>
            </div>
            <form method="POST" action="process.php">
                <div class="row">
                    <div class="col-md-12">
                        <input type="text" class="form-control" id="email" name="email" placeholder="Enter username" value="<?php if(isset($_COOKIE["username"])) { echo base64_decode($_COOKIE["username"]); } ?>" />
                    </div>
                </div>
                <div class="row">
                    <div class="col-md-12">
                        <input type="password" class="form-control" id="password" name="password" placeholder="Enter password" />
                    </div>
                </div>
                <div class="row">
                    <div class="col-md-12">
                        <input type="checkbox" id="remember_me" name="remember_me" <?php if(isset($_COOKIE["username"])) { ?> checked <?php } ?> />
                        Remember Me
                    </div>
                </div>
                <div class="row">
                    <div class="col-md-12" style="text-align:center">
                        <button type="submit" class="btn btn-primary">LOGIN</button>
                    </div>
                </div>
            </form>
        </div>
    </body>
</html>

Explanation of Index.php

  • HTML Login Form is created with two input fields of username and password, one checkbox for Remember Me function and one LOGIN Button.
<form method="POST" action="process.php">
     <input type="text" class="form-control" id="email" name="email" placeholder="Enter username" />
     <input type="password" class="form-control" id="password" name="password" placeholder="Enter password" />
     <input type="checkbox" id="remember_me" name="remember_me" <?php if(isset($_COOKIE["username"])) { ?> checked <?php } ?> />
     Remember Me
     <button type="submit" class="btn btn-primary">LOGIN</button>
</form> 
  • When user clicks on the LOGIN button, variables are posted to the process.php for further processing.
<form method="POST" action="process.php">
  • If session is already set, LOGIN page is not allowed to open and following instructions are coded for that.
<?php
    @session_start();
    if(isset($_SESSION['user_id']) && is_numeric($_SESSION['user_id'])){
        header("Location:welcome.php");
    }
?>

In order to use, PHP Super Global Variable $_SESSION on any page, we need to first start the session using session_start() method. If session is set, user is moved to the Welcome Page.

  • “Users” table is created inside “mydb” database and we have also inserted some dummy rows for login. It may look like:

Where, user_id is the primary key of the table and is unique to every user.

Status : 1 refers to active users, 0 refers to the inactive users.

  • In case of any error message generated, which is supposed to be displayed on Login Page, the following error code is specified:
<?php
     if(isset($_SESSION['msg']) && $_SESSION['msg'] != ''){
           echo "<p class='error'>".$_SESSION['msg']."</p>";
           unset($_SESSION['msg']);
     }
?>

                  

If $_SESSION[‘msg’] is set and is not void, the message is displayed on the screen and then we have unset the $_SESSION[‘msg’] variable so that, it should not display the same error message again and again on reloading.


process.php⬇

<?php
    include_once 'includes/conn.php';
    @session_start();
    $error = 1;
    $email = $_POST['email'];
    $email = filter_var($email, FILTER_SANITIZE_EMAIL);
    $email = filter_var($email, FILTER_VALIDATE_EMAIL);
    $password = $_POST['password'];
    $sql = "SELECT * FROM users WHERE email = '".$email."' AND STATUS = '1'";
    if(!isset($_COOKIE["username"])) {
        $sql .= " AND password = '" . $password . "'";
        $error = 0;
    }else{
        $email_cookie = base64_decode($_COOKIE['username']);
        if($email == $email_cookie){
            $error = 0;
        }
    }
    $exe = mysqli_query($con, $sql);
    $num_row = mysqli_num_rows($exe);
    
    if($num_row > 0 && $error == 0){
        $row = mysqli_fetch_assoc($exe);
        $_SESSION['user_id'] = $row['user_id'];
        $_SESSION['username'] = $row['name'];
        $_SESSION['msg'] = '';
        if(!empty($_POST["remember_me"])){
            $hour = time() + 3600 * 24 * 30;
            setcookie('username', base64_encode($email), $hour);
        }else{
            if(isset($_COOKIE["username"])){
                setcookie("username","");
            }
        }
        header("Location:welcome.php");
    }else{
        $_SESSION['msg'] = "Invalid Username or Password";
        header("Location:index.php");
    }    
?>

Explanation of process.php

  • Connection file is included in process.php file which creates a connection with mydb database.
<?php
    $con = new mysqli("localhost","root","","mydb");
    if ($con->connect_errno) {
        echo "Failed to connect to MySQL: ".$con->connect_error;
        exit();
    }
?> 
  • Form values are posted here which are further validated and stored in local variables $email and $password.
$email = $_POST['email'];
$email = filter_var($email, FILTER_SANITIZE_EMAIL);
$email = filter_var($email, FILTER_VALIDATE_EMAIL);
$password = $_POST['password'];
  • User record is fetched from the users table by using WHERE clause in MySQL Query as:
$sql = "SELECT * FROM users WHERE email = '".$email."' and STATUS = '1'"; 
  • If cookie with key username is not set password condition is concatenated. Otherwise, username cookie is decoded and is matched with email ID of user.
if(!isset($_COOKIE["username"])) {
    $sql .= " AND password = '" . $password . "'";
    $error = 0;
}else{
    $email_cookie = base64_decode($_COOKIE['username']);
    if($email == $email_cookie){
        $error = 0;
    }
} 
  • If user is authenticated Session is created and also if user has checked the remember me option then cookies are also created and the user is moved to welcome page.
$_SESSION['user_id'] = $row['user_id'];
$_SESSION['username'] = $row['name'];
$_SESSION['msg'] = '';
if(!empty($_POST["remember_me"])){
    $hour = time() + 3600 * 24 * 30;
    setcookie('username', base64_encode($email), $hour);
}else{
    if(isset($_COOKIE["username"])){
       setcookie("username","");
    }
}
   header("Location:welcome.php");

setcookie() php function is used to set a new cookie carrying the encoded username value for a particular time period.


welcome.php

<?php
    @session_start();
    if(!($_SESSION['user_id'])){
        $_SESSION['msg'] = "Please login your details.";
        header("Location:index.php");
    }
?>
<!DOCTYPE html>
<html>
    <head>
        <title>LOGIN</title>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
        <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
    </head>
    <body>
        <div class="container">
            <div class="row">
                <div class="col-md-8">
                    <h3>Hello, <?=$_SESSION['username']?></h3>
                    <h4>Welcome to our website.</h4>
                </div>
                <div class="col-md-4" style="padding-top: 20px">
                    <a href="logout.php">LOGOUT</a>
                </div>
            </div>
        </div>
    </body>
</html> 

Explanation of welcome.php

  • If session is not set, User is moved to Login Page. This instruction is set on all the pages which are User Specific. Code may look like.
if(!($_SESSION['user_id'])){
        $_SESSION['msg'] = "Please login your details.";
        header("Location:index.php");
}
  • Welcome page is coded according to the requirement of our website. We have simply displayed a welcome message to our User alongwith user’s name. A LOGOUT button is also specified on this page.

logout.php

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

Explanation of logout.php

  • session_destroy() method is used to empty all the variables in a session array. But if you want to destroy a single session variable then unset() method is used.                                                                                                                         
  • Header() in-built PHP method is used to redirect the user to Login Page.

Summary

In this project, we have learned to add remember me functionality in LOGIN Page. Cookies are used in PHP which stores the encoded username value in cookie and is used to authenticate the user while login.

Help Us to Improve our content

Let's Talk