Home >Backend Development >PHP Tutorial >How to Reliably Manage PHP Session Expiry After 30 Minutes?
The need for maintaining a session alive for a specific time and then terminating it is common in web development. PHP provides options for setting session timeouts, but they may not always yield reliable results. Let's understand the shortcomings of existing PHP mechanisms and explore a reliable solution.
PHP offers two options for setting session timeouts:
To establish a reliable session timeout, implement your own solution. This can be achieved by maintaining a time stamp representing the last user activity.
if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > 1800)) { // Last request was more than 30 minutes ago session_unset(); // Unset $_SESSION variable session_destroy(); // Destroy session data in storage } $_SESSION['LAST_ACTIVITY'] = time(); // Update last activity timestamp
As updating session data with each request modifies the session file's modification date, the garbage collector won't prematurely remove the session.
For added security, consider periodically regenerating the session ID to mitigate session hijacking attempts:
if (!isset($_SESSION['CREATED'])) { $_SESSION['CREATED'] = time(); } else if (time() - $_SESSION['CREATED'] > 1800) { // Session started more than 30 minutes ago session_regenerate_id(true); // Change session ID and invalidate old one $_SESSION['CREATED'] = time(); // Update creation time }
The above is the detailed content of How to Reliably Manage PHP Session Expiry After 30 Minutes?. For more information, please follow other related articles on the PHP Chinese website!