PHP Session Lifetime: A work around session.gc_maxlifetime
I needed to limit my session life time in a specific site running in my remote server. But could not set session.gc_maxlifetime. Also I know that session.gc_maxlifetime is not good! It is not reliable and it's tricky to get a different session max life time for each site running in your server.
So I made my own script that would clean session and cookies after a predefined number of minutes. Then all I had to do is to include this script in the start of my index.php:
So I made my own script that would clean session and cookies after a predefined number of minutes. Then all I had to do is to include this script in the start of my index.php:
// checks if session is idle for too much time
// if it is it will erase all session vars!
// if not it will update last activity time
// returns true if session was wiped
function session_check() {
// time out in seconds
$max_idle_time = 10 * 60;
// name of session variable used to store last activity
$sname = '_session_last_activity';
$cleaned = false;
// start session if it wasn't yet
if (session_id() == '') session_start();
// check if session variable is set
if (isset($_SESSION[$sname])) {
$t_old = $_SESSION[$sname];
$t_now = mktime();
// check if session expired
if ($t_now - $t_old > $max_idle_time) {
// wipe sessions
session_unset();
session_destroy();
$_SESSION = array();
// wipe cookies
foreach ($_COOKIE as $key => $value) setcookie($key, '',
time()-1);
$cleaned = true;
}
}
// create or refresh session
$_SESSION[$sname] = mktime();
return $cleaned;
}
// call funtion
if (session_check()) {
// echo 'Session was just cleaned...';
}