How to Expire a PHP Session

Here, we are going to provide you with a step-by-step guide on how to expire a PHP session. Let’s imagine that you intend to expire the user’s session after 30 minutes.

The best way to do that with PHP is to act manually. So, let’s try to expire a PHP session manually. Here is what you should do:

Watch a course Learn object oriented PHP

<?php

//Beginning the session.
session_start();

//Expiring the session in case the user is inactive for 30
//minutes or more.
$expireAfter = 30;

//Test to make sure if our "last action" session
//variable was set.
if (isset($_SESSION['last_action'])) {
    //Find out how many seconds have already passed
    //since the user was active last time.
    $secondsInactive = time() - $_SESSION['last_action'];

    //Converting the minutes into seconds.
    $expireAfterSeconds = $expireAfter * 60;

    //Test to make sure if they have not been active for too long.
    if ($secondsInactive >= $expireAfterSeconds) {
        // The user has not been active for too long.
        //Killing the session.
        session_unset();
        session_destroy();
    }
}

//Assigning the current timestamp as the user's
// the latest action
$_SESSION['last_action'] = time();

?>

Below, you can find the explanation of the code above.

Every session should be started with session_start(). Note, that the session variables cannot be accessed until the start of the session. In the case above, the limit is set to 30 minutes. However, you are free to change the limit to 60 or 40 minutes.

The isset function is applied for checking whether there is a variable called “last_action”.

The $expireAfter variable is converted to seconds by multiplying to 60. Then, the two values are compared to check whether the user has been inactive for too long. In case, $secondsInactive is larger or equal to $expireAfterSeconds, then the user has been inactive too long.

Afterward, you should kill the current session with the session_unset and session_destroy functions.