Session handling is a basic requirement for any type PHP based web project. If the project requires user registration and login options, then it is necessary to implement session handling feature for the project. How to create session and handle session for a particular user by using PHP and MySQL are shown in this tutorial by using very easy steps.
The tasks of this tutorial are divided in the following parts:
1. Prepare Database
2. Prepare File Structure
3. Create Configuration Files
4. Create custom CSS file
5. Create Template Files
6. Create and Validate Registration Form
7. Create and Validate Login Form
8. Create Admin Page
9. Create Register User Page
Prepare Database
A. Create a new database named “php_session”
B. Create two tables named users and session
CREATE TABLE `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`firstname` varchar(32) NOT NULL,
`lastname` varchar(32) NOT NULL,
`email` varchar(64) NOT NULL,
`contact_number` varchar(64) NOT NULL,
`password` varchar(512) NOT NULL,
`type` varchar(10) NOT NULL,
`status` int(4) NOT NULL,
`created` datetime NOT NULL,
`modified` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (id)
);
CREATE TABLE `session` (
`email` varchar(64) NOT NULL,
`session_id` varchar(100) NOT NULL,
`login_time` time NOT NULL,
`session_expire` time NOT NULL,
PRIMARY KEY (email)
);
C. Insert some data to users table
INSERT INTO `users` (`id`, `firstname`, `lastname`, `email`, `contact_number`, `password`, `type`, `status`, `created`, `modified`) VALUES
(1, 'Fahmida', 'Yesmin', 'fahmida@example.com', '88033333333', '96e79218965eb72c92a549dd5a330112', 'user', 1, '2019-01-01 00:00:00', '2019-06-13 18:17:47'),
(2, 'Administrator', '', 'admin@example.com', '88033333333', '96e79218965eb72c92a549dd5a330112', 'user', 1, '2019-01-01 00:00:00', '2019-06-13 18:17:47');
Prepare File Structure
You have to create the following files and folders to complete this tutorial
─ admin/
─── index.php
─ config/
─── core.php
─── database.php
─ images/
─── login_icon.png
─── refresh.png
─── 0.png
─── 1.png
─── 2.png
─── 3.png
─── 4.png
─ css/
─── customer.css
─ js/
─── jquery.min.js
─── validation.js
─ php/
─── check_email.php
─── login_check.php
─── register.php
─ header.php
─ footer.php
─ index.php
─ logout.php
─ navigation.php
─ login_checker.php
─ users/
─── user.php
Create Configuration Files
core.php
<?php
// show error reporting
error_reporting(E_ALL);
// start php session
session_start();
// set your default time-zone
date_default_timezone_set('Asia/Manila');
// home page url
$home_url="http://localhost/session_handling/";
?>
database.php
<?php
$mysqli = new mysqli("localhost","root","","php_session");
if(!$mysqli) die("Unable to connect with the database");
?>
Create custom CSS file
Add the following code in customer.css file.
.margin-bottom-1em{ margin-bottom:1em; }
.width-30-percent{ width:30%; }
.margin-1em-zero{ margin:1em 0; }
.width-30-percent{ width:30%; }
.width-70-percent{ width:70%; }
.margin-top-40{ margin-top:40px; }
.text-align-center{ text-align:center; }
div#blueimp-gallery div.modal{ overflow: visible; }
.photo-thumb{
width:214px;
height:214px;
float:left;
border: thin solid #d1d1d1;
margin:0 1em 1em 0;
}
.form-signin{
max-width: 330px;
padding: 15px;
margin: 0 auto;
}
.form-signin .form-control{
position: relative;
font-size: 16px;
height: auto;
padding: 10px;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
.form-signin .form-control:focus{ z-index: 2; }
.form-signin input[type="text"]{
margin-bottom: -1px;
border-bottom-left-radius: 0;
border-bottom-right-radius: 0;
}
.form-signin input[type="password"]{
margin-bottom: 10px;
border-top-left-radius: 0;
border-top-right-radius: 0;
}
.account-wall{
margin-top: 40px;
padding: 40px 0px 20px 0px;
background-color: #ffffff;
box-shadow: 0 2px 10px 0 rgba(0, 0, 0, 0.16);
}
.login-title{
color: #555;
font-size: 22px;
font-weight: 400;
display: block;
}
.profile-img{
width: 96px;
height: 96px;
margin: 0 auto 10px;
display: block;
-moz-border-radius: 50%;
-webkit-border-radius: 50%;
border-radius: 50%;
}
.select-img{
border-radius: 50%;
display: block;
height: 75px;
margin: 0 30px 10px;
width: 75px;
-moz-border-radius: 50%;
-webkit-border-radius: 50%;
border-radius: 50%;
}
.select-name{
display: block;
margin: 30px 10px 10px;
}
.logo-img{
width: 96px;
height: 96px;
margin: 0 auto 10px;
display: block;
-moz-border-radius: 50%;
-webkit-border-radius: 50%;
border-radius: 50%;
}
Create Template Files
Add the jquery.min.js file in js folder before starting the next step.
header.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- set the page title, for seo purposes too -->
<title>Session Handling</title>
<!-- Bootstrap CSS -->
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<!-- admin custom CSS -->
<link href="http://localhost/session_handling/css/customer.css" rel="stylesheet" />
<script src= "http://localhost/session_handling/js/jquery.min.js"></script>
<script src= "http://localhost/session_handling/js/validation.js"></script>
<style>
.pb-modalreglog-container
{
margin-top: 100px;
}
.pb-modalreglog-legend
{
text-align: center;
}
.pb-modalreglog-input-group
{
margin: auto;
}
.pb-modalreglog-submit
{
margin-left: 5px;
}
.pb-modalreglog-form-reg
{
text-align: center;
}
.pb-modalreglog-footer p
{
text-align: center;
margin-top: 20px;
}
#pb-modalreglog-progressbar
{
border-radius: 2px;
}
</style>
</head>
<body>
<!-- include the navigation bar -->
<?php include_once 'navigation.php'; ?>
<!-- container -->
<div class="container">
<div class='col-md-12'>
<div class="page-header">
<center><h1>Session Handling using PHP, MySQL and JQuery</h1></center>
</div>
</div>
footer.php
</div>
<!-- jQuery library -->
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<!-- Bootstrap JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<p id="regmsg"></p>
<!-- end HTML page -->
</body>
</html>
index.php
<?php
// core configuration
include_once "config/core.php";
include_once "config/database.php";
// include login checker
$require_login=true;
//include_once "login_checker.php";
if(isset($_GET['v']))
{
$sid= session_id();
$mysqli->query("Delete from session where session_id='$sid'");
session_unset();
session_destroy();
}
// include page header HTML
include_once 'header.php';
echo "<div class='col-md-12'>";
// to prevent undefined index notice
$action = isset($_GET['action']) ? $_GET['action'] : "";
// if login was successful
if($action=='login_success'){
echo "<div class='alert alert-info'>";
echo "<strong>Hi " . $_SESSION['firstname'] . ", welcome back!</strong>";
echo "</div>";
}
// if user is already logged in, shown when user tries to access the login page
else if($action=='already_logged_in'){
echo "<div class='alert alert-info'>";
echo "<strong>You are already logged in.</strong>";
echo "</div>";
}
echo "</div>";
// footer HTML and JavaScript codes
include 'footer.php';
?>
navigation.php
<!-- navbar -->
<div class="navbar navbar-default navbar-static-top" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<!-- to enable navigation dropdown when viewed in mobile device -->
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<!-- Change "Your Site" to your site name -->
<a class="navbar-brand" href="<?php echo $home_url; ?>">Session Handling Example</a>
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<!-- link to the "Cart" page, highlight if current page is cart.php -->
<li>
<a href="<?php echo $home_url; ?>">Home</a>
</li>
</ul>
<?php
// check if users was logged in
if(isset($_SESSION['logged_in']) && $_SESSION['logged_in']==true){
?>
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">
<span class="glyphicon glyphicon-user" aria-hidden="true"></span>
<?php echo $_SESSION['firstname']; ?>
<span class="caret"></span>
</a>
<ul class="dropdown-menu" role="menu">
<li><a href="<?php echo $home_url; ?>logout.php">Logout</a></li>
</ul>
</li>
</ul>
<?php
}
/// if user was not logged in, show the "login" and "register" options
else{
?>
<ul class="nav navbar-nav navbar-right">
<li >
<?php
if(isset($_GET['sess_id']))
echo '<a href="http://localhost/session_handling/index.php?v=logout"><span class="glyphicon glyphicon-log-out pb-modalreglog-submit"></span> Log Out</a>';
else
echo '<a href="#" data-toggle="modal" data-target="#myModal2" ><span class="glyphicon glyphicon-log-in pb-modalreglog-submit"></span> Log In</a>';
?>
</li>
<li >
<a href="#" data-toggle="modal" data-target="#myModal1" >
<span class="glyphicon glyphicon-check pb-modalreglog-submit" ></span> Register
</a>
</li>
</ul>
<?php
}
?>
</div><!--/.nav-collapse -->
</div>
</div>
<!-- /navbar -->
logout.php
<?php
// core configuration
include_once "config/core.php";
// destroy session, it will remove ALL session settings
session_destroy();
//redirect to login page
header("Location: {$home_url}login.php");
?>
Now, Run the index.php file to see the output.
Top
Create and Validate Registration Form
Add registration form using modal in navigation.php.
<!-- Registration Modal -->
<div class="modal fade" id="myModal1" tabindex="0" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" >
<div class="modal-dialog modal-md">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h4 class="modal-title" id="myModalLabel">User Registration</h4>
</div>
<div class="modal-body">
<form name="regForm" id="regForm" method="post" >
<div class="form-group">
<div id="pb-modalreglog-progressbar"></div>
</div>
<div class="form-group">
<div id="ele1" class="input-group pb-modalreglog-input-group">
<span class="input-group-addon"><span class="glyphicon glyphicon-user"></span></span>
<input type="text" class="form-control" id="fname" name="fname" placeholder="First Name" value="" required >
</div>
</div>
<div class="form-group">
<div id="ele1" class="input-group pb-modalreglog-input-group">
<span class="input-group-addon"><span class="glyphicon glyphicon-user"></span></span>
<input type="text" class="form-control" id="lname" name="lname" placeholder="Last Name" value="" required >
</div>
</div>
<div class="form-group">
<div id="ele1" class="input-group pb-modalreglog-input-group">
<span class="input-group-addon"><span class="glyphicon glyphicon-user"></span></span>
<input type="text" class="form-control" id="contact" name="contact" placeholder="Contact No" value="" required >
</div>
</div>
<div class="form-group">
<div id="ele2" class="input-group pb-modalreglog-input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-envelope"></i></span>
<input type="email" class="form-control" name="email" class="log_email" id="email" autocomplete="off" value="" required placeholder="Email">
</div>
</div>
<div class="form-group">
<div id="ele3" class="input-group pb-modalreglog-input-group">
<span class="input-group-addon"><span class="glyphicon glyphicon-lock"></span></span>
<input type="password" class="form-control" placeholder="Password" name="password" id="password" autocomplete="off" value="" required >
</div>
</div>
<div class="form-group">
<div id="ele4" class="input-group pb-modalreglog-input-group">
<span class="input-group-addon"><span class="glyphicon glyphicon-lock"></span></span>
<input type="password" class="form-control" placeholder="Confirm Password" name="cpassword" id="cpassword" autocomplete="off" value="" required >
</div>
</div>
<div class="form-group" id="capdiv">
<label for="confirmpassword">Enter the captcha code</label><br/>
<img alt="captcha" name="vimg" id="captcha_code" />
<img src="images/refresh.png" alt="reload" class="refresh" id="capimg" />
<div id="ele5" class="input-group">
<span class="input-group-addon" id="basic-addon1"><i class="glyphicon glyphicon-cog" aria-hidden="true"></i></span>
<input type="text" class="form-control" placeholder="Captcha" name="captcha" id="captcha" autocomplete="off" value="" required>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<div >
<button type="button" class="btn btn-labeled btn-success" id="Regsubmit" ><span class="btn-label"><i class="fa fa-check" aria-hidden="true"></i></span>Submit</button>
<button type="button" class="btn btn-labeled" data-dismiss="modal"><span class="btn-label"><i class="fa fa-close" aria-hidden="true"></i></span>Close</button>
</div>
</div>
</div>
</div>
</div>
<!-- Registration modal -->
Add the following code in the validation.js.
/***JQuery code to check existing email***/
$(function () {
var imgarray = ["qGphJD","CAPTCHA","captcha","V3B5w3pw","Google"];
var rimg = new Image();
var index;
RandomImage()
function RandomImage()
{
index = Math.random();
index = Math.floor(index*10);
var l = imgarray.length-1;
if(index > l) index= index%l;
rimg.src = "http://localhost/session_handling/images/"+index+".png";
document.vimg.src= rimg.src;
}
$('#capimg').click(function ()
{
RandomImage()
});
var dataValid
$('#Logsubmit').click(validate_login);
$('#Regsubmit').click(validate_reg);
function check_empty(eleid,divid)
{
$(eleid).each(function ()
{
var cur = $(this);
$(divid).next().remove();
if ($.trim(cur.val()) == '')
{
$(divid).after('<div class="error" style="color:red">This field can not be empty</div>');
dataValid = false;
}
else if(eleid == '#captcha')
{
check_captcha(eleid,divid)
}
else if(eleid == '#password' || eleid == '#cpassword' )
{
if($.trim(cur.val()).length < 6)
{
$(divid).after('<div class="error" style="color:red">Password is not in correct format</div>');
dataValid = false;
}
else
{
if(document.getElementById("password").value != document.getElementById("cpassword").value && eleid == '#cpassword' )
{
$(divid).after('<div class="error" style="color:red">Password does not match</div>');
dataValid = false;
}
}
}
});
}
function check_captcha(eleid,divid)
{
$(eleid).each(function ()
{
var match_t = false;
var cur = $(this);
$(divid).next().remove();
for(var i=0; i<imgarray.length; i++)
{
if($.trim(cur.val()) == imgarray[i] && (i == index))
{
match_t = true;
break;
}
}
if(match_t == false)
{
$(divid).after('<div class="error" style="color:red">Invalid captcha entry</div>');
dataValid = false;
}
});
}
function check_email(eleid,divid,type)
{
dataValid = true;
$(eleid).each(function ()
{
var cur = $(this);
$(divid).next().remove();
if ($.trim(cur.val()) == '')
{
$(divid).after('<div class="error" style="color:red">This field can not be empty</div>');
dataValid = false;
}
else
{
var emailPattern = /^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/;
if (!emailPattern.test(cur.val()))
{
$(divid).after('<span class="error" style="color:red"> Invalid Email Id</span>');
dataValid = false;
}
}
if(type == 2)
{
$.post('http://localhost/session_handling/php/check_email.php', {'email' : cur.val()}, function(data) {
if(data)
{
$(divid).after('<span class="error" style="color:red">Email already exists</span>');
dataValid = false;
}
});
}
});
}
function validate_login()
{
dataValid = true;
check_empty('#lpassword','#logpass')
check_email('#lemail','#logemail',1)
if(dataValid)
{
var postdata = $('#logForm').serialize();
$.post('http://localhost/session_handling/php/login_check.php',postdata,
function(data)
{
if(data == false)
{
alert("Invalid email or password")
}
else
{
$('#myModa2').modal('toggle');
window.location.href = data
}
},
'html'
);
}
}
function validate_reg()
{
dataValid = true;
check_empty('#fname','#ele1')
check_email('#email','#ele2',1)
check_email('#email','#ele2',2)
check_empty('#password','#ele3')
check_empty('#cpassword','#ele4')
check_empty('#captcha','#ele5')
if(dataValid)
{
var postdata = $('#regForm').serialize();
$.post('http://localhost/session_handling/php/register.php',postdata,
function(data)
{
if(data)
{
$('#myModal1').modal('toggle');
$('#regmsg').html("<center><h2>Registration successfully completed</h2><p>Check your email to activate your account</p></center>");
}
},
'html'
);
}
}
});
Add the following code in register.php.
<?php
include_once("../config/database.php");
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$contact = $_POST['contact'];
$email = $_POST['email'];
$password = md5($_POST['password']);
$query = "Insert into users set firstname='$fname',lastname='$lname', contact_number='$contact', email='$email', password='$password'";
$result = $mysqli->query($query);
if($mysqli->affected_rows > 0 )
echo 1;
else
echo 0;
?>
Add the following code in check_email.php.
<?php
include("../config/database.php");
$query = "Select * from users where email='".$_POST['email']."'";
$result = $mysqli->query($query);
if($result->num_rows > 0)
{
echo true;
}
else
echo false;
Create and Validate Login Form
Add login form using modal in navigation.php.
<!-- Login modal -->
<div class="modal fade" id="myModal2" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" style="display:none">
<div class="modal-dialog modal-sm" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h4 class="modal-title" id="myModalLabel">User Login</h4>
</div>
<div class="modal-body">
<form name="logForm" id="logForm" method="post" >
<div class="form-group">
<img class='profile-img' src='images/login-icon.png'>
<div id="logemail" class="input-group pb-modalreglog-input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-envelope"></i></span>
<input type="email" class="form-control" id="lemail" class="log_email" name="lemail" placeholder="Email" autocomplete="off" value="" class="req mail">
</div>
</div>
<div class="form-group">
<div id="logpass" class="input-group pb-modalreglog-input-group">
<span class="input-group-addon"><span class="glyphicon glyphicon-lock"></span></span>
<input type="password" class="form-control" id="lpassword" name="lpassword" placeholder="Password" autocomplete="off" value="" class="req" >
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-labeled btn-success" id="Logsubmit" ><span class="btn-label"><i class="fa fa-check" aria-hidden="true"></i></span>Log In</button>
<button type="button" class="btn btn-labeled" data-dismiss="modal"><span class="btn-label"><i class="fa fa-close" aria-hidden="true"></i></span>Close</button>
</div>
</div>
</div>
</div>
<!-- Login modal -->
Add the following code in login_check.php.
<?php
include("../config/core.php");
include("../config/database.php");
$pass=md5($_POST['lpassword']);
$query = "Select * from users where email='".$_POST['lemail']."' and "."password='".$pass."' and status=1";
//$query="Select * from users where email='fahmida@gmail.com' and password='111111'";
$result = $mysqli->query($query);
if($result->num_rows == 0)
{
echo false;
}
else
{
$mysqli->query("delete from session where email=".$_POST['lemail']);
session_unset();
session_destroy();
session_start();
$row=$result->fetch_assoc();
$_SESSION['email']=$row['email'];
$_SESSION['id']=session_id();
$_SESSION['firstname']=$row['firstname'];
if($row['type'] == 'admin')
echo $home_url."admin/index.php?email=".$row['email'];
else
echo $home_url."users/user.php?email=".$row['email'];
}
?>
Create Admin Page
Add the following code in admin/index.php.
<?php
include_once("../config/database.php");
session_start();
if(isset($_GET['email']))
{
if(isset($_SESSION['id']))
{
$query = "Select * from session where session_id='".$_SESSION['id']."'";
$result = $mysqli->query($query);
if($result->num_rows > 0)
{
$row=$result->fetch_row();
$current_time=date("h:i");
if($current_time>$row[3])
{
$mysqli->query("Delete from session where session_id=".$_SESSION['id']);
die("Your session is expired");
}
$email = $row[0];
//$result = $mysqli->query("Select * from users where email='$email'");
//$row=$result->fetch_row();
echo "<center><h3>Welcome to Administrator Page</h3>" ;
echo "<a href='http://localhost/session_handling/index.php?sess_id=".$_SESSION['id']."'>Home</a>";
echo " ";
echo "<a href='http://localhost/session_handling/index.php?v=logout>Logout</a></center>";
}
else
{
$query = "Select firstname,lastname,email from users where email='".$_GET['email']."'";
$result = $mysqli->query($query);
$row=$result->fetch_assoc();
echo "<center><br/><br/><h3>Welcome to Administrator Page</h3>" ;
echo "<a href='http://localhost/session_handling/index.php?sess_id=".$_SESSION['id']."'>Home</a>";
echo " ";
echo "<a href='http://localhost/session_handling/index.php?v=logout'>Logout</a></center>";
$login_time=date("h:i");
//expired_time = date("h:i", strtotime('+30 minutes', strtotime("now")));
$insqry="Insert into session set login_time='$login_time', email='".$_GET['email']."',session_id='".$_SESSION['id']."'";
$result = $mysqli->query($insqry);
}
}
else
die ("Your session is expired");
}
else
echo "<center><h2>You are not logged in or your session is expired</h2></center>";
?>
Now, again run the project from the browser.
Create Register User Page
Add the following code in users/user.php.
<?php
include_once("../config/database.php");
include_once("../config/core.php");
if(isset($_GET['email']))
{
if(isset($_SESSION['id']))
{
$query = "Select * from session where session_id='".$_SESSION['id']."'";
$result = $mysqli->query($query);
if($result->num_rows > 0)
{
$row=$result->fetch_row();
$current_time=date("h:i");
if($current_time>$row[3])
{
$mysqli->query("Delete from session where session_id=".$_SESSION['id']);
die("Your session is expired");
}
$email = $row[0];
$result = $mysqli->query("Select * from users where email='$email'");
$row=$result->fetch_assoc();
echo "<center><h3>Welcome back ".$row['firstname']." ".$row['lastname']."</h3>" ;
echo "<a href='".$home_url."index.php?sess_id=".$_SESSION['id']."'>Home</a>";
echo " ";
echo "<a href='".$home_url."index.php?v=logout>Logout</a></center>";
}
else
{
$query = "Select firstname,lastname,email from users where email='".$_GET['email']."'";
//$query="Select * from users where email='fahmida@gmail.com' and password='111111'";
$result = $mysqli->query($query);
$row=$result->fetch_assoc();
echo "<center><br/><br/><h3>Welcome ".$row['firstname']." ".$row['lastname']."</h3>" ;
echo "<a href='".$home_url."index.php?sess_id=".$_SESSION['id']."'>Home</a>";
echo " ";
echo "<a href='".$home_url."index.php?v=logout'>Logout</a></center>";
$login_time=date("h:i");
$expired_time = date("h:i", strtotime('+30 minutes', strtotime("now")));
$insqry="Insert into session set login_time='$login_time', email='".$_GET['email']."',session_id='".$_SESSION['id']."',session_expire='$expired_time'";
$result = $mysqli->query($insqry);
}
}
else
die ("Your session is expired");
}
else
echo "<center><h2>You are not logged in or your session is expired</h2></center>";
?>
Now, again run the project from the browser.
Conclusion
Hope, this tutorial helps the new web developers to create session for their web project.