How to Expire a PHP Session
On this page, we are going to provide you with a step-by-step guide on how to expire a PHP session after 30 minutes.
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:
php expire session after 30 minutes
<?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();
exit;
}
}
// Assigning the current timestamp as the user's latest action
$_SESSION['last_action'] = time();
?>Below, you can find the explanation of the code above.
Every session should be started with <kbd class="highlighted">session_start()</kbd>. 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 <kbd class="highlighted">$expireAfter</kbd> variable is converted to seconds by multiplying by 60. Then, the two values are compared to check whether the user has been inactive for too long. In case, <kbd class="highlighted">$secondsInactive</kbd> is larger or equal to <kbd class="highlighted">$expireAfterSeconds</kbd>, then the user has been inactive too long.
Afterward, you should kill the current session with the session_unset and session_destroy functions.
Note: For production environments, consider using the session.gc_maxlifetime directive in php.ini as a standard server-level alternative to manual timeout logic.