Remember me option allows the user to automatically get logged in to the website without entering its username and password again.
To do this I am using $_COOKIE that store value on the client-side for detecting the user. Next time when the user comes it will automatically redirect to the homepage.
Encrypt the value before storing it to $_COOKIE and decrypt it while access. It will automatically destroy after 30 days.
Contents
1. Table structure
I am using users
table in the example.
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 for the database configuration.
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. Login Page
HTML
Create a login form that has two input elements for entering username and password, a submit button, and a checkbox for 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" /> Remember Me </div> <div> <input type="submit" value="Submit" name="but_submit" /> </div> </div> </form> </div>
PHP
Created two functions to encrypt and decrypt the userid –
- encryptCookie() – This function takes a single parameter. Generate random key and assign to $key. I am using
'aes-256-cbc'
cipher (You can view other methods here). Encrypt value by passing value to openssl_encrypt().
Append $ciphertext
with $iv
and $key
separated by '::'
and encode in base64 format and return it.
- decryptCookie() – This function takes a single parameter. Explode the
$ciphertext
by'::'
and assign to variables.
Pass values in openssl_decrypt()
function and return it.
If $_SESSION['userid']
is see then redirect to home.php
file otherwise check if $_COOKIE['rememberme']
is set or not.
If set then decrypts the COOKIE value to get the userid. Check if $userid
exists in the users
table or not. If exists then assign $userid
to $_SESSION['userid']
and redirect to home.php
.
Form submit
Check if the username and password exist in the users
table or not. If exists then assign user id to $userid
variable.
If 'rememberme'
is POST then encrypt the userid and set 'rememberme'
COOKIE for 30 days.
Assign $userid
to $_SESSION['userid']
and redirect to home.php
.
Completed Code
<?php 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 = hex2bin(openssl_random_pseudo_bytes(4)); $cipher = "aes-256-cbc"; $ivlen = openssl_cipher_iv_length($cipher); $iv = openssl_random_pseudo_bytes($ivlen); $ciphertext = openssl_encrypt($value, $cipher, $key, 0, $iv); return( base64_encode($ciphertext . '::' . $iv. '::' .$key) ); } // Decrypt cookie function decryptCookie( $ciphertext ) { $cipher = "aes-256-cbc"; list($encrypted_data, $iv,$key) = explode('::', base64_decode($ciphertext)); return openssl_decrypt($encrypted_data, $cipher, $key, 0, $iv); } // 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"; } } }
4. Homepage
Within the homepage, I created a logout button.
On logout, button click destroy the $_SESSION
and $_COOKIE
variable and redirect to index.php file.
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 set the COOKIE expiry time according to your requirement.
You can view the PDO version of this tutorial here.
If you found this tutorial helpful then don't forget to share.