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 onwards 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.
Prerequisites

PHP
MySQL
Apache http Server

Please follow the below steps

Step 1. Create a table user_account in MySQL database

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

 

insert  into `user_account`(`account_id`,`account_login`,`account_password`,`user_name`,`user_email`,`last_login`) values (1,'user','ee11cbb19052e40b07aac0ca060c23ee ','soumitra','contact@roytuts.com','2015-06-13 07:36:07');

Step 2. Create a php configuration file config.php for various configurations

<?php

ini_set('display_errors', 'On');

error_reporting(E_ALL);

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

// 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", 1); //specify cookie timeout in days

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

/*
* End of file config.php
*/

Step 3. 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 dbAffectedRows() {
    global $dbConn;
    return mysqli_affected_rows($dbConn);
}

function dbFetchArray($result, $resultType = MYSQLI_NUM) {
    return mysqli_fetch_array($result, $resultType);
}

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

function dbFetchRow($result) {
    return mysqli_fetch_row($result);
}

function dbFreeResult($result) {
    return mysqli_free_result($result);
}

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

function dbNumFields($result) {
    return mysqli_num_fields($result);
}

function dbInsertId() {
    global $dbConn;
    return mysqli_insert_id($dbConn);
}

function closeConn() {
    global $dbConn;
    mysqli_close($dbConn);
}

/*
* End of file database.php
*/

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

<?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 (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() + 60 * 60 * 24 * COOKIE_TIME_OUT);
            setcookie("cookpass", $_SESSION['user_pass'], time() + 60 * 60 * 24 * COOKIE_TIME_OUT);
            setcookie("cookrem", $_SESSION['user_rem'], time() + 60 * 60 * 24 * COOKIE_TIME_OUT);
        } else {
            //destroy any previously set cookie
            setcookie("cookname", '', time() - 60 * 60 * 24 * COOKIE_TIME_OUT);
            setcookie("cookpass", '', time() - 60 * 60 * 24 * COOKIE_TIME_OUT);
            setcookie("cookrem", '', time() - 60 * 60 * 24 * 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.
    //delete from cookie if expires
    setcookie("cookname", '', time() - 60 * 60 * 24 * COOKIE_TIME_OUT);
    setcookie("cookpass", '', time() - 60 * 60 * 24 * COOKIE_TIME_OUT);
    setcookie("cookrem", '', time() - 60 * 60 * 24 * COOKIE_TIME_OUT);
    header('Location: ' . WEB_ROOT . 'login.php');
    exit;
}

/*
 * End of common.php
 */

Step 5. Create a login.php page where a user will input username and password for login

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

Step 6. 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>

Step 7. Create a logout.php page for logging out from the system.

<?php

require_once 'config.php';

user_logout();

/*
 * End of file logout.php
 */

That’s all. Thanks for reading.

Tags: •

Leave a Reply

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