4

I found many tutorials on Internet when you expire a session after a certain limit, like after 30 minutes or so, But I want to expire a session when there is no activity, quoting from a famous SO question the solution is straight forward:

if (isset($_SESSION['LAST_ACTIVITY']) 
    && (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
    }
$_SESSION['LAST_ACTIVITY'] = time(); // update last activity time stamp

but do I have to update the $_SESSION['LAST_ACTIVITY'] on each request?

The pre-assumed answer is Yes, but I have a big site containing 200+ php pages and it's hectic to update $_SESSION['LAST_ACTIVITY'] on each request.

Is there any other way of doing this? The only common thing among all files is one config file for DB connection.

Community
  • 1
  • 1
  • Search for every occurrence of `session_start()` and add the code after that. Better: Push your code snippet into a function or better a class and only call that class. – Sven Oct 07 '13 at 00:06

2 Answers2

8

You could also update the $_SESSION['LAST_ACTIVITY'] only (eg) once per minute but than the session will not be destroyed after exactly 30 minutes.

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
    }
}

And the easiest way to do this is put the code in the config file since I don't think you want to change all 200 php files.

Simon Fischer
  • 1,178
  • 6
  • 10
1

Corrected syntax..

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    
    }
}
Rizeen
  • 1,296
  • 1
  • 6
  • 17