Friday 28 September 2018

Pop-up Login Form If Session Expired using PHP Ajax



This is the most common feature of any website, if user has accidentally logout from system or his session has been expired and in browser still open website inner page then login modal has been popup for prevent to access inner pages of website without login into system. This type of feature we have make in this post by using PHP with Ajax. So, If Session has been expired or Session timeout then automatically login modal form will be pop up on web page to prevent to access website inner pages, and without login into system user cannot access that open page. This type of functionality is for accidentally logout from system in one tab or browser and in another website private pages has been open. So, in that pages login modal form will be popup on web page to tell user you are logout from system and if you want to access this you want to again login into system. In most of current website use this type of feature for accidentally logout from system or session timeout or expired.

If you have make website using PHP then you can easily implement this type of functionality into your system, so it will add one new feature in your website. You can easily build this type of feature in PHP using Ajax and jQuery. By using Ajax jQuery with PHP we can easily popup login modal form on web page when PHP session timeout. In this post we have step by step describe how best way we can handle Session expired with Ajax and popup login modal form for give notification to user your logout from system and to access system you have to login again into system on web page.

First we have to make simple login form for get access into system, For make login form we have use Ajax with PHP for validate user details. When user have filled login details then Ajax request will be send to check_login.php file to validate user information is proper or not. If details is not proper then it will display error on login page otherwise page will be redirect to index.php. Below you can find source code for login.php and check_login.php.



Database



--
-- Database: `testing`
--

-- --------------------------------------------------------

--
-- Table structure for table `tbl_login`
--

CREATE TABLE `tbl_login` (
  `id` int(11) NOT NULL,
  `first_name` varchar(100) NOT NULL,
  `last_name` varchar(100) NOT NULL,
  `gender` varchar(30) NOT NULL,
  `email` varchar(200) NOT NULL,
  `password` varchar(200) NOT NULL,
  `address` text NOT NULL,
  `mobile_no` varchar(15) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `tbl_login`
--

INSERT INTO `tbl_login` (`id`, `first_name`, `last_name`, `gender`, `email`, `password`, `address`, `mobile_no`) VALUES
(1, 'John', 'Smith', 'male', 'johnsmith@gmail.com', '$2y$10$vgo3NI5w5cLB74E4B2sdVuKwdSpJL/EAeKSUdevkc/j3zl0sJAf5i', 'test address', '9632587410');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `tbl_login`
--
ALTER TABLE `tbl_login`
  ADD PRIMARY KEY (`id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `tbl_login`
--
ALTER TABLE `tbl_login`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;


login.php



<?php  

//login.php
session_start();
if(isset($_SESSION["name"]))
{
 header('location:index.php');
}

?>  
<!DOCTYPE html>  
<html>  
    <head>  
  <title>Login Modal Popup After Session Timeout in PHP using Ajax</title> 
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />  
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
        <style> 
  body
  {
   background-color:#f1f1f1;
  }
        #box  
        {  
            width:500px;
   background-color:#ffffff;
            margin:0 auto;  
            padding:16px;  
            text-align:center;  
            margin-top:50px;
   border:1px solid #ccc;
   border-radius:5px;
        }  
        </style>  
 </head>  
 <body>  
  <div class="container">
   <br />
   <br />
   <h1 align="center">Login Modal Popup After Session Timeout in PHP using Ajax</h1>
   <div id="box">
    <h2>Login</h2>
    <br />
    <span id="error_message"></span>
    <form method="post" id="login_form">
     <input type="text" name="email" placeholder="Enter Email" class="form-control" required /><br />
     <input type="password" name="password" placeholder="Enter Password" class="form-control" required /><br />
     <input type="submit" name="submit" id="submit" class="btn btn-info" value="Login" />
    </form>
    <br /><br />  
   </div>
  </div>
    </body>  
</html>

<script>
$(document).ready(function(){
 $('#login_form').on('submit', function(event){
  event.preventDefault();
  $.ajax({
   url:"check_login.php",
   method:"POST",
   data:$(this).serialize(),
   success:function(data){
    if(data != '')
    {
     $('#error_message').html(data);
    }
    else
    {
     window.location = 'index.php';
    }
   }
  })
 });
});
</script>


check_login.php



<?php

//check_login.php

if(isset($_POST["email"]))
{
 $connect = new PDO("mysql:host=localhost;dbname=testing", "root", "");

 session_start();

 $query = "SELECT * FROM tbl_login WHERE email = '".$_POST['email']."'";

 $statement = $connect->prepare($query);

 $statement->execute();

 $total_row = $statement->rowCount();

 $output = '';

 if($total_row > 0)
 {
  $result = $statement->fetchAll();

  foreach($result as $row)
  {
   if(password_verify($_POST["password"], $row["password"]))
   {
    $_SESSION["name"] = $row["first_name"];
   }
   else
   {
    $output = '<label class="text-danger">Wrong Password</label>';
   }
  }
 }
 else
 {
  $output = '<label class="text-danger">Wrong Email Address</label>';
 }

 echo $output;
}

?>








In check_login.php page we can see for validate password details we have use password_verify() function, because in database password has been stored under hash format, so for validate hash password we have use password_verify() function and user first name details has been store into $_SESSION variable for check user has login into system and this variable value we can access from any page of system.

Once user has successfully login into system then he will be redirect to index page. On this page can be view only to login user for this we have check $_SESSION variable value is set or not, if this variable value is set then he can view this page otherwise it will be redirect to login page again. But if $_SESSION variable value is set then he can access this page, now here we will make login modal code and make one jQuery function for check user $_SESSION variable value is set or not.

index.php



<!DOCTYPE html>  
<html>  
    <head>  
        <title>Login Modal Popup After Session Timeout in PHP using Ajax</title> 
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />  
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
        <style>  
        #box  
        {  
            width:600px;
            color:white;  
            margin:0 auto;  
            padding:10px;  
            text-align:center;  
        }  
        </style>  
    </head>  
    <body>
 <br />

    <?php  
    session_start();  
    if(isset($_SESSION["name"]))
    {  
  echo "<h1 align='center'>Login Modal Popup After Session Timeout in PHP using Ajax</h1>";
        echo "<h1 align='center'>".$_SESSION["name"]."</h1>";  
        echo "<p align='center'><a href='logout.php'>Logout</a></p>";  
    }  
    else  
    {  
        header('location:login.php');  
    }  
    ?>  
    </body>  
</html>

<div class="modal fade" id="loginModal" role="dialog">
    <div class="modal-dialog modal-sm">
  <div class="modal-content">
   <div class="modal-header">
    <h4 class="modal-title">Session Expired Login Again</h4>
   </div>
   <div class="modal-body">
    <form method="post" id="login_form">  
     <input type="text" name="email" placeholder="Enter Email" class="form-control" required /><br />  
     <input type="password" name="password" placeholder="Enter Password" class="form-control" required /><br />  
     <input type="submit" name="submit" id="submit" class="btn btn-info" value="Login" />  
    </form>
   </div>
  </div>
    </div>
</div>

<script>  
$(document).ready(function(){
 
 var is_session_expired = 'no';
    function check_session()
    {
        $.ajax({
            url:"check_session.php",
            method:"POST",
            success:function(data)
            {
    if(data == '1')
    {
     $('#loginModal').modal({
      backdrop: 'static',
      keyboard: false,
     });
     is_session_expired = 'yes';
    }
   }
        })
    }
 
 var count_interval = setInterval(function(){
        check_session();
  if(is_session_expired == 'yes')
  {
   clearInterval(count_interval);
  }
    }, 10000);
 
 $('#login_form').on('submit', function(event){
  event.preventDefault();
  $.ajax({
   url:"check_login.php",
   method:"POST",
   data:$(this).serialize(),
   success:function(data){
    if(data != '')
    {
     $('#error_message').html(data);
    }
    else
    {
     location.reload();
    }
   }
  });
 });

});  
</script>


Here in index.php file we have make login modal form with id #loginModal. This modal will be popup if PHP Session expired and for check Session timeout or not. For this here we have make check_session() function which send Ajax on every 10 seconds to check_session.php for check Session variable value expired or not. For call check_session() on every seconds we have use setInterval() method. By using this method it will call jQuery function every 10 seconds. Once modal has been popup then after stop to called check_session() we have use clearInterval() method.

check_session.php



<?php  
 
//check_session.php
 
session_start();

if(isset($_SESSION["name"]))
{
 echo '0';
}
else
{
 echo '1';
}

?>


This is PHP script to check $_SESSION variable value is set or not for check session timeout using isset() function. Lastly for logout from system below you can find logout.php code. In which session variable value has been destroy using session_destroy() function. After logout from system page will be redirect to login.php.


<?php  

//logout.php
 
session_start();

session_destroy();

header("location:login.php");

?>


This is complete step by step process for how to create feature like Login form popup on web page if user Session timeout or expired using PHP script with Ajax jQuery.

4 comments: