Automatic Logout after 15 minutes of inactive in php

Viewed 103911

I want to destroy session if users are not doing any kind of activity on website. At that time after 5 users automatically redirect on index page. How is it possible? Is possible in php with session handling and for that I have to maintain or update user login time or not..

8 Answers

I got this solution from Sitepoint.com Using a simple meta tag in your html

<meta http-equiv="refresh" content="900;url=logout.php" />

The 900 is the time in seconds that you want the session to be terminated if inactive.

Hope it works for you

Edit: This method does not implement any other logic so will only work if you want to "force" logout as said in the comments

You may create a cookie for a specific time. For example you could put this on your login page:

<?php
  setcookie('admin', 'abc', time()+50); 
?>

Then in some file part that is included in every page, like 'header.php', you may include:

<?php
  if (!isset($_COOKIE['admin'])) {
  echo "<script> location.href='logout.php'; </script>";   
  }

  setcookie('admin', 'abc', time()+50);
?>

In the above example, after 50s the cookie will die and the user will be logged out automatically.

This code was included in the connection.php to ensure that the code is included in any page but you can implement on any page you want

if (isset($_SESSION['user-session']) OR isset($_SESSION['admin-session']) ) {
//then we are checking the activity sesssion $_SESSION['']
if (isset($_SESSION['last_active'])) {

    //if the time is set then we check the difference
    $max_time=5*60; #number of seconds
    $now=microtime(date("H:i:s"));
    //Checking the last active  and now difference in seconds
    $diff=round(microtime(date("H:i:s"))- $_SESSION['last_active']); #the difference of time
    if ($diff>=$max_time) { #if the difference is greater than the allowed time!
        //echo "logging out couse the time is".$diff;
        header("location:logout.php");          
    }else {
        $time=microtime(date("H:i:s"));
    $_SESSION['last_active']=$time; #Updating the time 
    //echo 'More time added the time was!'.$diff;
    }
}else{
    //if there is no last active then we create it over here
    $time=microtime(date("H:i:s"));
    $_SESSION['last_active']=$time;
}}

Simple solution using .htaccess

Add the below lines to your .htaccess file where 3600 is the number of seconds. Sessions will automatically be destroyed after certain time has nothing to do with the activity or inactivity.

According to the below code session will be destroyed after 1 hour.

php_value session.gc_maxlifetime 3600

php_value session.gc_probability 1

php_value session.gc_divisor 1
Related