PHP ini_set session gc_maxlifetime not working

andytt picture andytt · Mar 19, 2014 · Viewed 14.1k times · Source

I am trying to set gc_maxlifetime in PHP.

Here is the code in 'header.php', and I include it every page.

ini_set('session.cookie_lifetime', 1);
ini_set('session.gc_maxlifetime', 1);
session_start();

I test it with

echo ini_get('session.gc_maxlifetime');

and it does set to 1.

But it still keep login status, that is, session has not been deleted.

What is the possible reason?

Answer

hank picture hank · Mar 19, 2014

Why doesn't Garbage Collection run?

GC does not always run on every request, default PHP settings is that it is 1% chance to run GC. session.gc_probability (default 1) / session.gc_divisor (default 100) = 0.01 (1% chance)

Relevant manual entry: http://php.net/manual/en/session.configuration.php#ini.session.gc-probability

My suggestion is to store last time a session was touched and check against that value on every page load and if enough time has passed, session_destroy and redirect user to login page.