To maintain a session for a specific amount of time and terminate it afterward, implementing a custom session timeout is recommended. This approach is more reliable than relying on session settings such as session.gc_maxlifetime or session.cookie_lifetime.
1. session.gc_maxlifetime:
session.gc_maxlifetime determines the amount of time after which session data is deemed 'garbage' and removed. However, garbage collection occurs sporadically, making it an unreliable method for session expiration.
2. session.cookie_lifetime:
session.cookie_lifetime only influences the lifespan of the cookie sent to the browser, not the session itself. The server is responsible for invalidating sessions, not the client.
Recommended Solution:
Implement a custom session timeout by maintaining a time stamp that tracks the last activity time. Update this time stamp with every request.
if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > 1800)) { // last request was more than 30 minutes ago session_unset(); // unset $_SESSION variable for the run-time session_destroy(); // destroy session data in storage } $_SESSION['LAST_ACTIVITY'] = time(); // update last activity time stamp
This method effectively expires session data after 30 minutes of activity and prevents premature removal by the garbage collector.
For enhanced security, consider periodically regenerating the session ID to prevent session fixation attacks.
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 for the current session and invalidate old session ID $_SESSION['CREATED'] = time(); // update creation time }
Notes:
The above is the detailed content of How Can I Effectively Expire a PHP Session After 30 Minutes of Inactivity?. For more information, please follow other related articles on the PHP Chinese website!