This tutorial will show you how to login to an application with remember me functionality. Sometimes we need to remember username and password for few days or years so that next time onward a user can login without entering the username and password into the input fields. The username and password fields get populated automatically from the cookie where the username and password are kept for few days or years.

An http cookie is a small piece of data sent from a website and stored on the user’s computer by the user’s web browser while the user is browsing.

Cookies were designed to be a reliable mechanism for websites to remember stateful information or to record the user’s browsing activity.

Prerequisites

PHP 7.3.5, MySQL 8.0.17, Apache HTTP Server 2.4

Create MySQL Table

Create a table user_account in MySQL server under roytuts database.

CREATE TABLE `user_account` (
  `account_id` int unsigned NOT NULL AUTO_INCREMENT,
  `account_login` varchar(25) NOT NULL,
  `account_password` varchar(255) NOT NULL,
  `user_name` varchar(30) NOT NULL,
  `user_email` varchar(100) NOT NULL,
  `last_login` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`account_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

Dump User Details

We don’t want to create any new user through our application, so we will dump a user details using SQL statement.

The encrypted password is user. This password is encrypted using md5() function but it’s not a concrete method to encrypt your password and try to use more strong encryption mechanism.

insert  into `user_account`(`account_id`,`account_login`,`account_password`,`user_name`,`user_email`,`last_login`) values (1,'user','ee11cbb19052e40b07aac0ca060c23ee ','soumitra','[email protected]','2020-01-21 07:36:07');

Create Project Directory

It’s assumed that you have setup Apache, PHP and MySQL in Windows system.

Now we will create a project root directory called php-mysql-login-logout-remember-me under the Apache server’s htdocs folder.

Related Posts:

We may not mention the project root directory in subsequent sections and we will assume that we are talking with respect to the project root directory.

Application Configurations

Create a php configuration file config.php for various application related configurations.

<?php

ini_set('display_errors', 'On');

error_reporting(E_ALL);

//database connection config
$dbHost = 'localhost';
$dbUser = 'root';
$dbPass = 'root';
$dbName = 'roytuts';

// setting up the web root and server root
$thisFile = str_replace('\\', '/', __FILE__);
$docRoot = $_SERVER['DOCUMENT_ROOT'];

$webRoot = str_replace(array($docRoot, 'config.php'), '', $thisFile);
$srvRoot = str_replace('config.php', '', $thisFile);

define('WEB_ROOT', $webRoot);
define('SRV_ROOT', $srvRoot);

define("COOKIE_TIME_OUT", 5*60); //specify cookie timeout in minutes

require_once 'database.php';
require_once 'common.php';

/*
* End of file config.php
*/

Database Configurations

Create database.php file for various database operations.

<?php

$dbConn = mysqli_connect($dbHost, $dbUser, $dbPass, $dbName) or die('MySQL connect failed. ' . mysqli_connect_error());

function dbQuery($sql) {
    global $dbConn;
    $result = mysqli_query($dbConn, $sql) or die(mysqli_error($dbConn));
    return $result;
}

function dbFetchAssoc($result) {
    return mysqli_fetch_assoc($result);
}

function dbNumRows($result) {
    return mysqli_num_rows($result);
}

/*
* End of file database.php
*/

Common Functionalities

Create common.php file for various common functionalities to be performed.

This function defines few common functionalities, such as, login, logout, whether user’s credentials exist in cookie and eligible for auto-populate of input fields in login form.

<?php

function check_login() {
    /* Check if user has been remembered */
    if (isset($_COOKIE['cookname'])) {
        $_SESSION['user_name'] = $_COOKIE['cookname'];
    }

    if (isset($_COOKIE['cookpass'])) {
        $_SESSION['user_pass'] = $_COOKIE['cookpass'];
    }

    if (isset($_COOKIE['cookrem'])) {
        $_SESSION['user_rem'] = $_COOKIE['cookrem'];
    }

    /* Username and password have been set */
    if (isset($_SESSION['user_name']) && isset($_SESSION['user_pass'])) {
        /* Confirm that username and password are valid */
        if (confirm_user($_SESSION['user_name'], $_SESSION['user_pass']) === FALSE) {
            /* Variables are incorrect, user not logged in */
            unset($_SESSION['user_name']);
            unset($_SESSION['user_pass']);
            unset($_SESSION['user_rem']);
            return FALSE;
        }
		
        $row = dbFetchAssoc(confirm_user($_SESSION['user_name'], $_SESSION['user_pass']));
        $_SESSION['user_id'] = $row['account_id'];
        $_SESSION['last_login'] = $row['last_login'];
		
        return TRUE;
    } else {/* User not logged in */
        return FALSE;
    }
}

//user login
function user_login($username, $password) {
	if (check_login() === TRUE) {
		header('Location:' . WEB_ROOT . 'home.php');
		exit;
	} else {
		if (user_exists($username) === FALSE) {
			return "You are not a registered member";
		} else if (confirm_user($username, md5($password)) === FALSE) {
			return "Authentication error";
		} else {
			$_SESSION['user_name'] = $username;
			$_SESSION['user_pass'] = $password;
			
			$row = dbFetchAssoc(confirm_user($username, md5($password)));
			
			$_SESSION['user_id'] = $row['account_id'];
			$_SESSION['last_login'] = $row['last_login'];
			
			if (isset($_POST['remember_me'])) {
				$_SESSION['user_rem'] = $_POST['remember_me'];
				setcookie("cookname", $_SESSION['user_name'], time() + COOKIE_TIME_OUT);
				setcookie("cookpass", $_SESSION['user_pass'], time() + COOKIE_TIME_OUT);
				setcookie("cookrem", $_SESSION['user_rem'], time() + COOKIE_TIME_OUT);
			} else {
				//destroy any previously set cookie
				setcookie("cookname", '', time() - COOKIE_TIME_OUT);
				setcookie("cookpass", '', time() - COOKIE_TIME_OUT);
				setcookie("cookrem", '', time() - COOKIE_TIME_OUT);
			}

			//Login history
			$sql = "UPDATE user_account
					SET last_login=now()
					WHERE account_login='" . $username . "'";

			dbQuery($sql);

			header('Location:' . WEB_ROOT . 'home.php');
			exit;
		}
	}
}

function user_exists($username) {
    $sql = "SELECT ua.account_login,ua.user_name,ua.last_login
            FROM user_account ua
            WHERE (ua.account_login='$username' OR ua.user_email='$username')"
            . " LIMIT 1";

    $result = dbQuery($sql);

    if (!$result || (dbNumRows($result) < 1)) {
        return FALSE; //Indicates username failure
    }

    return $result;
}

function confirm_user($username, $password) {
    /* Verify that user is in database */
    $sql = "SELECT ua.account_login,ua.user_name,ua.last_login
            FROM user_account ua
            WHERE (ua.account_login='$username' OR ua.user_email='$username')
                AND ua.account_password='$password' LIMIT 1";

    $result = dbQuery($sql);

    if (!$result || (dbNumRows($result) < 1)) {
        return FALSE; //Indicates username failure
    }

    return $result;
}

//do user logout
function user_logout() {
    session_start();
    $_SESSION = array(); // reset session array
    session_destroy();   // destroy session
	
    header('Location: ' . WEB_ROOT . 'login.php');
    exit;
}

/*
 * End of common.php
 */

Login Page

Create a login.php page where a user will input username and password for login. We have also placed remember me checkbox if user wants to remember his/her credentials into cookie.

<?php
require_once 'config.php';

$temp = '';
$errors = '';
$clss = 'error';
if (isset($_POST['login'])) {
    $username = trim($_POST['username']);
    $password = trim($_POST['password']);

    if (empty($username) || empty($password)) {
        $errors .= "\nEmail/Username and Password required.";
        $temp.="N";
    }

    if (!empty($username) && strlen($username) > 80) {
        $errors .= "\nMax length of Email Address:80";
        $temp.="N";
    }

    if ((!empty($password) && strlen($password) > 20)) {
        $errors .= "\nMax length of Password:25";
        $temp.="N";
    }

    if (empty($temp)) {
        $_POST['password'] = '';
        $_POST['email'] = '';
        //$clss = 'success';
        $result = user_login($username, $password);
        $errors .= $result;
    }
}
?>
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>Remember Me Example</title>
        <style type="text/css">
            .error {
                color: red;
            }
            .success {
                color: green;
            }
        </style>
    </head>
    <body>
        <form method="post"
              action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>">
                  <?php
                  if (!empty($errors)) {
                      echo "<p class='" . $clss . "'>" . nl2br($errors) . "</p>";
                  }
                  ?>
            <h3>Login</h3>
            <div>
                <input type="text" name="username" title="Username/Email"
                       tabindex="1" autocomplete="off"
                       value="<?php echo isset($_COOKIE['cookname']) ? $_COOKIE['cookname'] : @htmlspecialchars($_POST['username']); ?>"/>
            </div>
            <div>
                <input type="password" name="password" title="Password" tabindex="2"
                       autocomplete="off" value="<?php echo isset($_COOKIE['cookpass']) ? $_COOKIE['cookpass'] : ''; ?>"/>
            </div>
            <p>
                <label>
                    <input type="checkbox" name="remember_me" tabindex="3"
                           value="1" <?php echo isset($_COOKIE['cookrem']) ? 'checked="checked"' : ''; ?>
                           autocomplete="off"/>&nbsp;Remember me
                </label>
            </p>
            <div>
                <input type="submit" name="login" value="Login" tabindex="4"/>
            </div>
        </form>
    </body>
</html>

Home Page

Create home.php page that a user will see after a successful login.

<?php
require_once 'config.php';
?>
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>My Home</title>
    </head>
    <body>
        Welcome! You have successfully logged in. Thank you.
        <a href="<?php echo WEB_ROOT; ?>logout.php" onclick="return confirm('Are you sure want to logout?')">Logout</a>
    </body>
</html>

Logout

Create a logout.php page for logging out from the application.

<?php

require_once 'config.php';

user_logout();

/*
 * End of file logout.php
 */

Testing the Application

Now we will test our application to check whether the application is working as expected or not.

Hit URL http://localhost/php-mysql-login-logout-remember-me/login.php in the browser to see the login page:

php login logout remember me

If you now put credentials user/user in the input fields with Remember me checkbox selected then when you logout from the application and on next visit of login page you will see input fields are auto-populated:

php login logout remember me

The login credentials are remembered into cookie only for 5 minutes and after 5 minutes you won’t be able to see the input fields auto-populated.

On home page when you want to logout you will get a popup for confirmation whether you really want to logout or not.

php login logout remember me

Source Code

Download

That’s all. Thanks for reading.

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *