You’re running Debian Linux or Ubuntu Linux. You want PHP sessions to last longer than the default 1440 seconds (24 minutes). So you do this:
ini_set('session.gc_maxlifetime', 10800); # 3 hours
With this setting, sessions should remain active for at least three hours, as long as users don’t close their browser.1
But no matter what you do, sessions keep getting deleted after 24–54 minutes. It seems PHP is ignoring the
Why this happens
Debian and Ubuntu Linux override PHP’s session behavior. If you look closely, you’ll see that
session.gc_probability is set to
0, meaning PHP’s garbage collection will never run. Instead, there’s a Debian-specific
cron job in
/etc/cron.d/php5 that runs every 30 minutes!
cron job does garbage collection based on the global
session.gc_maxlifetime in your app is ignored.
While you could disable the
cron job and/or modify
php.ini, I’d prefer to fix the problem without modifying system defaults. A better solution is to create your own sessions directory, somewhere outside the normal one, and then locally enable PHP’s session garbage collection.
To do this, set
# Session lifetime of 3 hours ini_set('session.gc_maxlifetime', 10800); # Enable session garbage collection with a 1% chance of # running on each session_start() ini_set('session.gc_probability', 1); ini_set('session.gc_divisor', 100); # Our own session save path; it must be outside the # default system save path so Debian's cron job doesn't # try to clean it up. The web server daemon must have # read/write permissions to this directory. session_save_path(APP_PARENT_DIR . '/sessions'); # Start the session session_start();
php.ini, but there are several reasons not to.
php.inichanges things globally, not just for your application. And if someone else changes it, your application could break. Finally, if you ever need to deploy your application on another server, you would have to remember to change the setting in the new server’s
php.ini. I always prefer
ini_set()and never modify
php.iniexcept as a last resort. ↩