Login page with Remember me in PHP

Remember me option allow the user to automatically get logged in to the website without entering its username and password again.

To do this I am using $_COOKIE which store value on the client side for detecting the user. Next time when the user come it will automatically redirect to the homepage.

Encrypt the value before storing it in $_COOKIE and decrypt it while access. It will automatically destroy after 30 days.

Login page with Remember me in PHP


Contents

  1. Table structure
  2. Configuration
  3. HTML
  4. PHP
  5. Conclusion

 


 

1. Table structure

I am using users table.

CREATE TABLE `users` (
  `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
  `username` varchar(80) NOT NULL,
  `password` varchar(20) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

 

2. Configuration

Create a new config.php file.

Completed Code

<?php
session_start();
$host = "localhost"; /* Host name */
$user = "root"; /* User */
$password = ""; /* Password */
$dbname = "tutorial"; /* Database name */

$con = mysqli_connect($host, $user, $password,$dbname);

// Check connection
if (!$con) {
 die("Connection failed: " . mysqli_connect_error());
}

 

3. HTML

Creating a login form which has two input elements for entering username and password, a submit button and a checkbox for enabling Remember me.

Completed Code

<div class="container">
 <form method="post" action="">
  <div id="div_login">
  <h1>Login</h1>
  <div>
  <input type="text" class="textbox" name="txt_uname" placeholder="Username" />
  </div>
  <div>
  <input type="password" class="textbox" name="txt_pwd" placeholder="Password"/>
  </div>
  <div>
  <input type="checkbox" name="rememberme" value="1" />&nbsp;Remember Me
  </div>
  <div>
  <input type="submit" value="Submit" name="but_submit" />
  </div>
  </div>
 </form>
</div>

 

4. PHP

Initialize $_SESSION and $_COOKIE

Initializing $_SESSION['userid'] when the entered username and password matched in MySQL database table and initialize $_COOKIE['rememberme'] when Remember me checkbox is being checked.

Encrypt $_COOKIE

Before assigning a value to $_COOKIE I encrypt it for this I created encryptCookie() function and set its expire time to 30 days.

Check values

Check $_SESSION and $_COOKIE variable when the user next time come to the login page.

First, check $_SESSION variable is set or not if set then redirect the user to home.php.

If $_SESSION is not set then check $_COOKIE variable.

For decrypt the encrypted value I created decryptCookie() function and check the return value in MySQL database table. If value found then redirect to home.php.

Completed Code

include "config.php";

// Check if $_SESSION or $_COOKIE already set
if( isset($_SESSION['userid']) ){
 header('Location: home.php');
 exit;
}else if( isset($_COOKIE['rememberme'] )){
 
 // Decrypt cookie variable value
 $userid = decryptCookie($_COOKIE['rememberme']);
 
 $sql_query = "select count(*) as cntUser,id from users where id='".$userid."'";
 $result = mysqli_query($con,$sql_query);
 $row = mysqli_fetch_array($result);

 $count = $row['cntUser'];

 if( $count > 0 ){
  $_SESSION['userid'] = $userid; 
  header('Location: home.php');
  exit;
 }
}

// Encrypt cookie
function encryptCookie( $value ) {
 $key = 'youkey';
 $newvalue = base64_encode( mcrypt_encrypt( MCRYPT_RIJNDAEL_256, md5( $key ), $value, MCRYPT_MODE_CBC, md5( md5( $key ) ) ) );
 return( $newvalue );
}

// Decrypt cookie
function decryptCookie( $value ) {
 $key = 'youkey';
 $newvalue = rtrim( mcrypt_decrypt( MCRYPT_RIJNDAEL_256, md5( $key ), base64_decode( $value ), MCRYPT_MODE_CBC, md5( md5( $key ) ) ), "\0");
 return( $newvalue );
}

// On submit
if(isset($_POST['but_submit'])){

 $uname = mysqli_real_escape_string($con,$_POST['txt_uname']);
 $password = mysqli_real_escape_string($con,$_POST['txt_pwd']);
 
 if ($uname != "" && $password != ""){

  $sql_query = "select count(*) as cntUser,id from users where username='".$uname."' and password='".$password."'";
  $result = mysqli_query($con,$sql_query);
  $row = mysqli_fetch_array($result);

  $count = $row['cntUser'];

  if($count > 0){
   $userid = $row['id'];
   if( isset($_POST['rememberme']) ){

    // Set cookie variables
    $days = 30;
    $value = encryptCookie($userid);
    setcookie ("rememberme",$value,time()+ ($days * 24 * 60 * 60 * 1000));
   }
 
   $_SESSION['userid'] = $userid; 
   header('Location: home.php');
   exit;
  }else{
   echo "Invalid username and password";
  }

 }

}

Homepage

Within the homepage, I created a logout button. Using it to destroy the $_SESSION and $_COOKIE variable when it gets button gets clicked.

Completed Code

<?php
 include "config.php";

// Check user login or not
 if(!isset($_SESSION['userid'])){
 header('Location: index.php');
}

// logout
if(isset($_POST['but_logout'])){
 session_destroy();

 // Remove cookie variables
 $days = 30;
 setcookie ("rememberme","", time() - ($days * 24 * 60 * 60 * 1000));

 header('Location: index.php');
}
?>
<h1>Homepage</h1>
<form method='post' action="">
 <input type="submit" value="Logout" name="but_logout">
</form>

 

5. Conclusion

For security purpose, I encoded the userid before storing it in a $_COOKIE and you can replace the key with your key which should be long enough so anyone couldn’t guess.

Related Post

Spread the love

4 Comments

  1. Roger Poole said:

    A little surprised that you used mysql_select_db vs mysqli_select_db.
    Might be time to update your code. This won’t fly in later versions of PHP.

    February 2, 2017
    Reply
    • Yogesh Singh said:

      Thank you for your response.
      I updated the code.

      February 3, 2017
      Reply
  2. Ajmal Praveen said:

    Hello Yogesh,
    2hrs ago i visited this page and
    Really your Code helps me to Understand some more Better. Added a Keep me logged in Feature in my Login system. with a Huge modification.

    A GUIDANCE and TIPS.
    I have Modified some More advanced like Token feature which Connects with DB
    * Added extra token cookie Which is sent to browser and Added to user DB ..
    * When he/she lost his PHP Session, Script will check for remember me cookie and token cookie and Match it with Server DB Token.
    * If it was Matched and Creating a new PHP Session for the user.
    * If not He/She need to Login again.

    and I can see you are mysqli non prepared statements, try to use PDO Prepared Placeholder Statements in my experience pdo is Faster and Better, Optimized according to the Usage Comparing mysqli > PDO wins..

    Hope you will give tutorials in PDO Prepared Statements.

    Thank you..
    Ajmal Praveen 😉

    September 7, 2017
    Reply
    • Yogesh Singh said:

      Hi Ajmal,
      Thanks for reading and a suggestion.
      I will try to write this tutorial in PDO also, so be sure to subscribe.

      September 8, 2017
      Reply

Leave a Reply

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