How to log out a user after 10 minutes of inactivity on the site

Hi, In this tutorial, I am going to teach you how to log out a user after 10 minutes of inactivity on the site.

Generally, we implement the logic like this when user logins authenticate the user information, If user information is a valid i.e username, email, and password then we will create the session for the user.

Then user session is maintained throughout the website. whenever a user logs out then we will remove the session of the user on the server. If a user doesn't log out from the site then his session never expired / removed automatically, we have to remove the session manually, In this situation, we can implement this mechanism i.e log out a user after 10 minutes of inactivity on the site.
In Session start page to set the login time in the session.

sessionStart.php
<?php  
 session_start(); //on pageload  
 $_SESSION['start_time'] = time(); //on session creation  
 $_SESSION["name"] = "TechiesBadi";  
 $_SESSION["email"] = "techiesbadi@gmail.com";  
 header('Location: home.php');  
?>  
isLoggedIn.php
<?php  
 session_start(); //on pageload  
 $timeout = 10; // Set timeout minutes  
 $logout_redirect_url = "index.php"; // Set logout URL  
 $timeout = $timeout * 60; // Converts minutes to seconds  
 if (isset($_SESSION['start_time'])) {  
   $elapsed_time = time() - $_SESSION['start_time'];  
   if ($elapsed_time >= $timeout) {  
     session_destroy();  
     header("Location: $logout_redirect_url");  
   }  
 }  
 $_SESSION['start_time'] = time();  
?>
include this isLoggedIn.php in your header page simply or you can add this entire code in header page. Then a user can log out the site after 10 minutes of inactivity on the site automatically.

* If you like this post please don’t forget to subscribe Techies Badi - programming blog for more useful stuff


EmoticonEmoticon