Skip to content
Advertisement

PHP sessions don’t expire. Ever

I’m transferring my application to another server, but I have some issues with the PHP sessions that don’t seem to expire.

In php.ini I’ve set:

session.gc_probability = 1
session.gc_divisor = 1
session.gc_maxlifetime = 300

Cookies are enabled, of course. And still, after 5 minutes, if I refresh the page I’m still logged in. Even if I close the browser and reopen the page. Edit: actually, it seems that closing the browser does clear the session.

Since every request passes through a certain script first (RewriteRule / begin.php), I’m quite lucky and I could get over the problem with this:

session_start();
if (time() > @$_SESSION['sessionLimit']) {
    session_destroy();
    session_start();
}
$_SESSION['sessionLimit'] = time() + ini_get('session.gc_maxlifetime');

But still, I don’t get what I’m doing wrong and why in the old server everything was fine (even if session.gc_divisor was set to 10).

Old server: Windows Server 2003, Apache 2.4, PHP 5.4.5, all 32 bit

New server: Windows Server 2008 R2, Apache 2.4, PHP 5.5.4, all 64 bit

Advertisement

Answer

Please see this answer: How do I expire a PHP session after 30 minutes?

Gumbo explains the matter better than I ever could.

In particular, Gumbo explains why session.gc_maxlifetime is not reliable and he recommends implementing session timeout yourself, using a simple time stamp that denotes the time of the last activity (i.e. request), and updating that timestamp 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
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement