The login page is the basic requirement for membership-based websites.
User needs to login to the website using its username or email and password to access the website. If the user has not logged out but the SESSION is destroyed then it needs to again login to the website.
By adding remember me on the login form the user needs to checked the remember me checkbox and login to the website. Now if the user has not logged out but the SESSION is destroyed.
When the user again accesses the website then it does not need to login and the SESSION is initiated.
In this tutorial, I show how you create a login page with remember me functionality with PDO and PHP.
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, `name` varchar(80) NOT NULL, `password` varchar(80) NOT NULL, ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
2. Configuration
Create a config.php
for a database connection.
Completed Code
<?php $server = "localhost"; $username = "root"; $password = ""; $dbname = "tutorial"; // Create connection try{ $conn = new PDO("mysql:host=$server;dbname=$dbname","$username","$password"); $conn->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION); }catch(PDOException $e){ die('Unable to connect with the database'); }
3. Login Page
Create index.php
file.
HTML
Create a <form >
.
Create a text element for username, a password element, a checkbox for remember me, and a submit button.
<!doctype html> <html> <head> <title>Login page with Remember me using PDO and PHP</title> <link href="style.css" rel="stylesheet" type="text/css"> </head> <body> <div class="container"> <form method="post" action=""> <div id="div_login"> <h1>Login</h1> <div> <input type="text" class="textbox" name="txt_uname" value="" placeholder="Username" /> </div> <div> <input type="password" class="textbox" name="txt_pwd" value="" placeholder="Password"/> </div> <div> <input type="checkbox" name="rememberme" value="1" /> Remember Me </div> <div> <input type="submit" value="Submit" name="but_submit" id="but_submit" /> </div> </div> </form> </div> </body> </html>
PHP
Created 2 functions to encrypt and decrypt the userid. I am using OpenSSL for encrypting and decrypting-
- encryptCookie – This function takes a single parameter which is userid. Generate random key, I am using
'aes-256-cbc'
cipher (You can view other methods here). Get the$iv
.
To encrypt pass values in openssl_encrypt
– openssl_encrypt($userid, $cipher, $key, 0, $iv)
.
Append $ciphertext
with $iv
and $key
separated by '::'
and encode in base64 format and return it.
- decryptCookie – This function takes a single parameter which is
$ciphertext
. Explode the$ciphertext
by'::'
and assign in variables.
Pass values in openssl_decrypt()
function and return it.
Login <form > submit and set remember me COOKIE –
If but_submit
is POST then read username and password. If the username and password are not empty then check username and password is exists in the users
table or not.
If exists then read the user id.
Set Remember me COOKIE if 'rememberme'
is POST. Encrypt the user id by calling encryptCookie()
function. Set the $_COOKIE['rememberme']
for 30 days.
Initialize $_SESSION['userid']
with $userid
and redirect to home.php
.
Check remember me COOKIE –
Check if $_SESSION['userid']
is set or not. If set then redirects to home.php
otherwise, check $_COOKIE['rememberme']
is set or not.
If set then decrypt the $_COOKIE['rememberme']
bypassing it in decryptCookie()
function and get the user id. Check if user id exists or not. If exists then set $_SESSION['userid']
and redirect to home.php
.
<?php include "config.php"; // 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); } // 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']); // Fetch records $stmt = $conn->prepare("SELECT count(*) as cntUser FROM users WHERE id=:id"); $stmt->bindValue(':id', (int)$userid, PDO::PARAM_INT); $stmt->execute(); $count = $stmt->fetchColumn(); if( $count > 0 ){ $_SESSION['userid'] = $userid; header('Location: home.php'); exit; } } // On submit if(isset($_POST['but_submit'])){ $username = $_POST['txt_uname']; $password = $_POST['txt_pwd']; if ($username != "" && $password != ""){ // Fetch records $stmt = $conn->prepare("SELECT count(*) as cntUser,id FROM users WHERE username=:username and password=:password "); $stmt->bindValue(':username', $username, PDO::PARAM_STR); $stmt->bindValue(':password', $password, PDO::PARAM_STR); $stmt->execute(); $record = $stmt->fetch(); $count = $record['cntUser']; if($count > 0){ $userid = $record['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
Create home.php
file.
Check if $_SESSION['userid']
is set or not. If not set then redirect to index.php
file.
On the page create a <form >
and a submit button for logout.
On logout, button click destroy the SESSION and remove the 'rememberme'
COOKIE by setting it time in the past.
Redirect to index.php
page.
Completed Code
<?php include "config.php"; ?> <!doctype html> <html> <head> <title>Login page with Remember me using PDO and PHP</title> </head> <body> <?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> </body> </html>
5. Conclusion
Comment the setcookie()
function on the logout button click in home.php
file to check if remember me is working or not and you can also reduce the expiration time of COOKIE.
If it is working then SESSION is created when running index.php
file and the page is redirected to home.php
file.
You can view the MySQLi version of this tutorial here.
You can also view the Registration form creation with MySQLi and PHP tutorial here.
If you found this tutorial helpful then don't forget to share.