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.

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.
 


 

 

CONVERSATION

0 Comments:

Post a Comment

Back
to top