user1765876
user1765876

Reputation:

expire session when there is no activity in PHP

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.

Upvotes: 4

Views: 11537

Answers (2)

Simon Fischer
Simon Fischer

Reputation: 1208

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.

Upvotes: 8

Rizeen
Rizeen

Reputation: 1344

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

Upvotes: 1

Related Questions