Php Tips
Session timeout
REF: https://solutionfactor.net/blog/2014/02/08/implementing-session-timeout-with-php/
So despite the session ini settings available, if you want a reliable session timeout, you’re forced to implement your own. Fortunately doing so is pretty easy.
First, set session.gc_maxlifetime to the desired session timeout, in seconds. E.g. if you want your sessions to timeout after 30 minutes, set session.gc_maxlifetime to 1800 (60 seconds in a minute * 30 minutes = 1,800 seconds). What this does is ensure a given session file on the server can live for at least that long.
Second, and what a lot of other posts out there don’t mention, is that you also need to set session.cookie_lifetime to at least the same value (1,800 seconds, in this case). Otherwise, the phpsessid cookie may expire before 30 minutes is up. If that happens, the cookie is removed and the client has no way of identifying its session id to the server anymore. That effectively terminates the session before our 30 minute session window.
Third, add the following code to your app’s entry point, or any point in your app that’s executed on every request (usually an index.php file, front controller, bootstrap file, etc.).
$time = $_SERVER['REQUEST_TIME'];
/**
* for a 30 minute timeout, specified in seconds
*/
$timeout_duration = 1800;
/**
* Here we look for the user's LAST_ACTIVITY timestamp. If
* it's set and indicates our $timeout_duration has passed,
* blow away any previous $_SESSION data and start a new one.
*/
if (isset($_SESSION['LAST_ACTIVITY']) &&
($time - $_SESSION['LAST_ACTIVITY']) > $timeout_duration) {
session_unset();
session_destroy();
session_start();
}
/**
* Finally, update LAST_ACTIVITY so that our timeout
* is based on it and not the user's login time.
*/
$_SESSION['LAST_ACTIVITY'] = $time;
What that does is keep track of the time a user’s session started. That’s tested on every request to see if their session has expired a 30 minute window. If so, a new session is created. This might also be where you’d handle re authenticating the user somehow, if needed, usually by giving them a login expired, or login UI, of some sort.