0

I am creating a website with more than 10 different php files. I want to check if the user is inactive, starting from the login page. So, if a user logs in and remains idle for a specific period of time, it has to log that user out. I am new to PHP and am currently using an answer to similar question which is

if (isset($_SESSION["LAST_ACTIVITY"])) {
   if (time() - $_SESSION["LAST_ACTIVITY"] > 1800)) {
      // last request was more than 30 minutes ago
      session_unset();     // unset $_SESSION variable for the run-time 
      session_destroy();   // destroy session data in storage
   } else if (time() - $_SESSION["LAST_ACTIVITY"] > 60) {
       $_SESSION["LAST_ACTIVITY"] = time(); // update last activity time stamp
    }
}

I found the answer here:

expire session when there is no activity in PHP

I have created a separate page called session.php and pasted the code in the above link. Then I included the file session.php in my login page (which checks for the credentials entered and logs a user in). The problem is, the if loop is not being run and I do not know how to define $_SESSION['LAST_ACTIVITY'] variable. I used the following in my login page:

$query = "SELECT * 
          FROM user_details 
          WHERE username = '$username' 
          AND password = '$password'";

  $result = mysqli_query($dbconnect, $query);
  $row = mysqli_fetch_array($result);

  $count = mysqli_num_rows($result);

  if ($count == 1) {
     session_start();
     echo "Welcome    " .$username. "</br>";
     $_SESSION['username'] = $username;
     $login_time = time();
     $_SESSION["LAST_ACTIVITY"] = $login_time   ;
     include('session.php');

I also tried including session.php at the beginning of the file but of no use. The problem is: time() - $_SESSION["LAST_ACTIVITY"] is being equalled to 0. How do I store last activity time and compare it with the current time? Also, should I include session.php in every other webpage file for the website to check user activity ? If yes, should I include it at the beginning or at the end ?

Ajay
  • 41
  • 1
  • 4

1 Answers1

1

This code will solved your problem for session timeout.

<?php
// set timeout period in seconds
$inactive = 60; //after 60 seconds the user gets logged out
// check to see if $_SESSION['timeout'] is set
if(isset($_SESSION['timeout']) ) {
$session_life = time() - $_SESSION['timeout'];
if($session_life > $inactive)
    { 
        session_destroy(); 
        header("Location: Logout.php"); 
    }
}
$_SESSION['timeout'] = time();

?>

Sushank Pokharel
  • 869
  • 7
  • 15
  • How do I initialize the value of $_SESSION['timeout']? Where does this piece of code get the value of $_SESSION['timeout'] to evaluate the first if loop? – Ajay Nov 28 '17 at 08:50
  • $_SESSION['timeout'] = time(); this will initialize the value of $_SESSION['timeout']. I have written this line after the end of the loop. – Sushank Pokharel Nov 28 '17 at 08:52