[Solved- 7 Answers] How to expire a PHP session after 30 minutes?
We need to keep a session alive for 30 minutes and then destroy it?
We need to implement our session timeout. The options are(session.gc_maxlifetime and
session.cookie_lifetime)(http://php.net/manual/en/session.configuration.php#ini.session.gc-maxlifetime) are not reliable
.First Option: session.gc_maxlifetime
session.gc_maxlifetime specifies the number of seconds after which data will be seen as ‘garbage’ and cleaned up. Garbage collection occurs during session start.
Second Option: session.cookie_lifetime
session.cookie_lifetime specifies the lifetime of the cookie in seconds which is sent to the browser.
Best solution:
Use a simple time stamp that denotes the time of the last activity (i.e. request) and update it with every request:
php code
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
[ad type=”banner”]
Updating the session data with every request also changes the session file’s modification date hence, the previous sessions are not removed from the data.
Use an additional time stamp to regenerate the session ID periodically to avoid attacks on sessions like session fixation:
php code
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 }
We can particle sessions after a certain lifespan by using the session.gc_maxlifetime( http://uk3.php.net/manual/en/session.configuration.php#ini.session.gc-maxlifetime)ini setting:
Now, Check if the timestamp is within the allowed time window (1800 seconds is 30 minutes)
php code
<?php session_start(); if( !isset( $_SESSION['user_id'] ) || time() - $_SESSION['login_time'] > 1800) { header("Location:login.php"); } else { // uncomment the next line to refresh the session, so it will expire after thirteen minutes of inactivity, and not thirteen minutes after login //$_SESSION['login_time'] = time(); echo ( "this session is ". $_SESSION['user_id'] ); //show rest of the page and all other content } ?>
Wikitechy Founder, Author, International Speaker, and Job Consultant. My role as the CEO of Wikitechy, I help businesses build their next generation digital platforms and help with their product innovation and growth strategy. I'm a frequent speaker at tech conferences and events.