How to expire a PHP session?

How to expire a PHP session?

This is a very common requirement to expire a PHP Session If a user is inactive on page for more than say `x` time and redirect him to the Login page to Authenticate himself again.

The best possible solution for that is to Manage the Session timeout by your own, by your server. The existing PHP Session configuration options like session.cookie_lifetime or session.gc_maxlifetime are not reliable and might not work for you. They solve a different purpose.

So, lets see how to do it:

 $maxInactivityDuration)) {
    // So we can say user was last active `$maxInactivityDuration` ago i.e. 30 Minutes
    // Unset the Session variable
    session_unset();
    
    // Destroys all data registered to a session
    session_destroy();   
    
    // Put your action here like Redirect user to Login Page
    // echo and return 0 is just to test the Script. Remove it before you use and put your action here.
    echo "SESSION DESTROYED";
    return 0;
}

// User is active, continue the flow, no need to redirect him.
// Just update the last active time to current
$_SESSION['LAST_ACTIVE'] = time(); 

// echo and return 0 is just to test the Script. Remove it before you use and put your action here.
echo "SESSION KEPT";
return 0;

?>

Hope this might help you. We will see in future posts that how to create a class that completely handles the sessions. So stay tuned and happy coding.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.