How to Expire a Session After Some Times of User Inactivity in PHP?

Solution: Learn how to expire a session after a certain amount of time of user's inactivity.

Problem:

You’ve a secure admin panel. You want to add an option that will automatically log you out after 15 minutes of your inactivity.

Solution

We can accomplish the task in two steps-

Step 1: Initialize a timer variable while you login

In your login verification page, add a session variable that will hold the login time. For this, you can add the following line -

<?php
     $_SESSION[‘last_acted_on’] = time();
?>

Explanation:
Save the time you login in the last_acted_on session variable. Here, time() function provides the current time.

Step 2: Check time difference with every click

After login when you click any link, check the time difference between the current time and the time saved in the last_acted_on session variable. If it is more than fifteen minutes, destroy the session variable and log you out. If not, update the session variable value with the new current time.

<?php
if( isset($_SESSION[‘last_acted_on’]) && (time() - $_SESSION[‘last_acted_on’] > 60*15) ){
    session_unset();     // unset $_SESSION variable for the run-time
    session_destroy();   // destroy session data in storage
    header('Location: path/to/login/page');
}else{
    session_regenerate_id(true);
    $_SESSION[‘last_acted_on’] = time();
}
?>

Explanation:

Line: 2
It checks whether last_acted_on session variable contains a value ( isset($_SESSION[‘last_acted_on’] ) ). If it does, the inactivity time (in seconds) is calculated subtracting last active time ($_SESSION[‘last_acted_on’]) from the current time ( time() ).  Then it checks If this time difference is more than 15 minutes.Line: 3
if you’re inactive for more than 15 minutes, then free all the specified session variables and, then,

Line: 4
destroy all the session data that stored, and at last,

Line: 5
redirect this page to the login page.

Line: 7
if you took action within last 15 minutes, regenerate new session id with session_regenerate_id(true) function (Here, true parameter deletes the old session id which helps to prevent session fixation attack) and,

Line: 8
then, set the current time in the last_acted_on session variable.



Pin It

↑ Back to Top