Automatic logout after 10 min of user Inactivity in page using PHP Mysql


Automatic Session Timeout, Automatic logout after 10 min of user Inactivity in page using PHP Mysql,  Auto expire session / Auto logout after specific

Hi friends, in this tutorial I will show you how to create an automatic wait / exit session using PHP after 10 minute of inactivity. Currently the most important session concept for logged in users. If the user forgets to leave the page, the security risk increases and there is the possibility of data theft by the user. In this case I created a session variable and stored the current time in the variable. If a user is inactive at the last minute, they will automatically log out of the system and be redirected to the login page. In this tutorial I will explain how to delete a session after 10 minutes of user inactivity with PHP.

Automatic Session Timeout, Automatic logout after 10 min of user Inactivity in page using PHP Mysql,  Auto expire session / Auto logout after specific

Create Database and Table by SQL query

In first step, we need to create database and table, so here I created “webscodex” database and “admins” table with id, name, username, password  and created column. You can simply create “admins” table as following SQL query.
-- Database: `webscodex`
--
-- --------------------------------------------------------
-- Table structure for table `admins`
--

CREATE TABLE `admins` (
  `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
  `name` varchar(50) NOT NULL,
  `username` varchar(50) NOT NULL,
  `password` varchar(50) NOT NULL,
  `created` datetime NOT NULL DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

--
-- Dumping data for table `admins`
--

INSERT INTO `admins` (`id`, `name`, `username`, `password`, `created`) VALUES
(1, 'manish', 'manish123', 'admin', '2021-01-30 20:24:31');

Create Database Configuration File.

In this step, we require to create database configuration file, here we will set database name, username and password. So let’s create “config.php” file on your root directory and put bellow code:
config.php
<?php

	// Database configuration 	
	$hostname = "localhost"; 
	$username = "root"; 
	$password = ""; 
	$dbname   = "webscodex";
	 
	// Create database connection 
	$con = new mysqli($hostname, $username, $password, $dbname); 
	 
	// Check connection 
	if ($con->connect_error) { 
	    die("Connection failed: " . $con->connect_error); 
	}

?>

Create Login HTML Page and PHP login Code

In this code, we are creating HTML Login page using bootstrap CDN link and code the login logic and store user session time and user name in Session variable for checking user inactivity in another page.
when user enter username and password is correct than redirect to dashboard or profile page.
index.php
<?php

// start session
session_start();

// Include database connectivity
  
include_once('config.php');

if (isset($_SESSION['NAME'])) {
   header("Location:dashboard.php");
   exit();
}

if (isset($_POST['submit'])) {

   $errorMsg = "";
  
   $username = $con->real_escape_string($_POST['username']);
   $password = $con->real_escape_string($_POST['password']);  
  
   if(!empty($username) && !empty($password)){

   $query = "SELECT * FROM admins WHERE username = '$username' AND password ='$password'";
    
   $result = $con->query($query);

   if($result->num_rows > 0) {
      $row = $result->fetch_assoc();
      $_SESSION['NAME'] = $row['name'];
      $_SESSION['LAST_ACTIVE_TIME'] = time();
      header("Location:dashboard.php");
      die();
   }

   else{
      $errorMsg = "Username or Password is Invalid";
   }
     
   }else{
      $errorMsg = "Username and Password is required";
   }

}    

?>
<!DOCTYPE html>
<html lang="en">
<head>
  <title>Automatic logout after 10 min of user Inactivity in page using PHP Mysql</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"> 
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> 
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</head>
<body>

<div class="card text-center" style="padding:20px;">
  <h3>Automatic logout after 10 min of user Inactivity in page using PHP Mysql</h3>
</div><br>

<div class="container">
  <div class="row justify-content-center">
    <div class="col-md-4 col-md-offset-4">
      <?php if (isset($errorMsg)) { ?>
        <div class="alert alert-danger alert-dismissible fade show">
          <button type="button" class="close" data-dismiss="alert">&times;</button>
          <?php echo $errorMsg; ?>
        </div>
      <?php } ?>
      <div class="card">
        <div class="card-body">
          <img class="card-img-top" src="img_avatar1.png" style="width:25%;border-radius:50%;margin-left:110px;">
          <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="POST">
            <div class="form-group">  
              <label for="username">Username:</label> 
              <input type="text" class="form-control" name="username" placeholder="Username">
            </div>
            <div class="form-group">  
              <label for="password">Password:</label> 
              <input type="password" class="form-control" name="password" placeholder="Password">
            </div>
            <div class="form-group">
              <input type="submit" name="submit" class="btn btn-primary btn-block" value="Login"> 
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>
</div>
</body>
</html>


Preview:

Automatic Session Timeout, Automatic logout after 10 min of user Inactivity in page using PHP Mysql,  Auto expire session / Auto logout after specific

Create Dashboard/Profile after login successful

In this code, we are create dashboard page using bootstrap and a modal popup, modal is hide, using AJAX jquery for send ajax request in check_user.php page for checking if user session time is expire than show the modal popup for 10 sec, after 10 sec modal popup close and redirect to the login page with out reloading page.
dashboard.php
 
<!doctype html>
<html lang="en">
    <head>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<title>Automatic logout after 10 min of user Inactivity in page using PHP Mysql</title>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">	   
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>	
	<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
    </head>
<body>
    <div class="container">
	<div class="row" style="margin-top:70px;">
            <?php
    	        include_once('check_user.php');
	    ?>
	    <div class="col-md-12 card text-center" style="padding:50px;">
	        <h3>Welcome <span class="text-success"><?php echo ucwords($_SESSION['NAME']); ?>
	        </span> to the Webs Codex</h3>
	        <h3>Automatic Logout after 10 minute of user Inactivity in page</h3>
	        <p><a href='logout.php'>Logout</a></p>
	    </div>
        </div>		
    </div>		
</body>
</html>

<!-- The Modal -->
<div class="modal" id="myModal">
  <div class="modal-dialog">
    <div class="modal-content">   
     	<!-- Modal Header -->
     	<div class="modal-header">
           <h4 class="modal-title">Session Expiration</h4>       
       	</div>     
	<!-- Modal body -->
    	<div class="modal-body">
           Because you have been Inactivity, your session is about to expire.
     	</div>     
	<!-- Modal footer -->
	<div class="modal-footer">
	   <a href="index.php" class="btn btn-primary btn-sm">Login again</a>     		
	</div>     
     </div>
  </div>
</div>

<script type="text/javascript">
  
setInterval(check_user, 2000);

function check_user(){
    $.ajax({
	url:'check_user.php',
   	method:'POST',      	
   	data:'type=logout',
   	success:function(result){ 
   	    if (result == "logout") {
	   	$("#myModal").modal({
	           backdrop: 'static',
	   	   keyboard: false,
	        });
	    setTimeout(function(){
	       $('#myModal').modal('hide')
	          window.location.href="logout.php";
	       }, 10000);				
	   }      	
   	}
   });
}

</script>

Before Session Active

Preview:

 
Automatic Session Timeout, Automatic logout after 10 min of user Inactivity in page using PHP Mysql,  Auto expire session / Auto logout after specific

 

After Session Expire

Preview:

Create check_user.php File for Check time

In this code we add the login user  time to enter the session variable. Then we call the PHP function to check if the login session expiration time has expired. If not reached, the user is redirected to the login page.
check_user.php
<?php

session_start();

if (isset($_POST['type']) && $_POST['type'] == 'logout') {
	
    if ((time() - $_SESSION['LAST_ACTIVE_TIME']) > 600) {  // 60*10 Time in Seconds		
		
	echo "logout";
    }

}else{
		
    if (isset($_SESSION['LAST_ACTIVE_TIME'])) {
    	if ((time() - $_SESSION['LAST_ACTIVE_TIME']) > 600) {  // 60*10 Time in Seconds
	    header("Location:logout.php");
	    die();
	}
    }

    $_SESSION['LAST_ACTIVE_TIME'] = time();

    if (!isset($_SESSION['NAME'])) {
	header("Location:index.php");
	die();
    }
}

?>

Create Users Logout File

This logout.php page “unset” entered user sessions.
logout.php
<?php		
	session_start();
	session_destroy();
	session_unset($_SESSION['NAME']);
	session_unset($_SESSION['LAST_ACTIVE_TIME']);
	header("Location:index.php");
	die();	
?>

You can always support by sharing on social media or recommending my blog to your friends and colleagues.

If you have any suggestions / problems about this tutorial, please comment on the  form below.😊


Leave a Reply