PHP Session Timeout Handling
When a user logs in to a PHP application, a session is often created to maintain their identity throughout their browsing session. However, it may be desirable to set a timeout on this session to automatically terminate it after a specified period of inactivity. This article explains how to configure and monitor session timeouts in PHP.
Setting a Session Timeout
To specify a timeout for a session, you can utilize PHP's configuration settings:
session_start([ 'cookie_lifetime' => 60 * $minutes ]);
In this example, $minutes specifies the desired duration of the session in minutes. After the specified time has elapsed, the session will expire.
Monitoring Session Timeout
To monitor session timeouts, you can track the last time a request was made by the user:
$_SESSION['timeout'] = time();
In subsequent requests, you can check how long it has been since the previous request:
if ($_SESSION['timeout'] + (10 * 60) < time()) { // Session has timed out } else { // Session is still active }
In this example, a session timeout of 10 minutes is enforced. If the time since the last request exceeds 10 minutes, the session is considered timed out.
By implementing these techniques, you can effectively manage session timeouts in your PHP application, ensuring that inactive sessions are terminated promptly.
The above is the detailed content of How to Configure and Monitor PHP Session Timeouts?. For more information, please follow other related articles on the PHP Chinese website!