Expire PHP Session After 30 Minutes
Question:
How can I create a PHP session that will expire after 30 minutes?
Answer:
Method: Implement Custom Session Timeout
PHP's built-in session timeout methods, such as session.gc_maxlifetime and session.cookie_lifetime, are unreliable due to various factors. Instead, implement your own timeout using:
if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > 1800)) { session_unset(); session_destroy(); } $_SESSION['LAST_ACTIVITY'] = time();
This code updates the session timestamp on every request, keeping the session file active and preventing premature deletion by the garbage collector.
Additional Security:
To protect against session hijacking, regenerate the session ID periodically:
if (!isset($_SESSION['CREATED'])) { $_SESSION['CREATED'] = time(); } else if (time() - $_SESSION['CREATED'] > 1800) { session_regenerate_id(true); $_SESSION['CREATED'] = time(); }
Notes:
The above is the detailed content of How to Make a PHP Session Expire After 30 Minutes of Inactivity?. For more information, please follow other related articles on the PHP Chinese website!