Thursday, January 14, 2016

php init_set session gc_maxlifetime doesn't work (solution VPS)





I had problems with changing the max session lifetime as it didn't work by just writing this to my php code:
ini_set('session.gc_maxlifetime', 8*60*60);
ini_set('session.cookie_lifetime', 8*60*60);
My goal was to set the session lifetime to 8 hours (8*60*60 = 28800 seconds). Still the sessions was destroyed after 1 hour or 3600 seconds. 3600 seconds is my default session gc_maxlifetime setting in php.ini ( /etc/php5/apache2/php.ini Ubuntu 14.04 ) and the default is 1440 seconds.
I confirmed that the parameter was actually changed with
ini_get('session.cookie_lifetime');
And yes. It was set to 28800 seconds. So what then if I could change the session.cookie_lifetime but it still doesn't work?

The problem was not anything with my settings. But with the default settings of how the system handles the garbage collection for the sessions that is stored on the server. There is a cron job that runs every X minute and a bash script that wipes out the old session, where the sessions are stored and based on the value set in the php.ini file, not the manual configuration I'm setting in my script.

So as long as I don't specify another save path for the session files, the default handler for the garbage collection will wipe those out.

One solution for this is to save the php sessions in another path:
ini_set('session.save_path', getcwd().'/../phpSessionStorage');
Now everything should work as expected. But one thing to keep in mind is that if you specify another save path for the php sessions then you need to remove all the old ones, some sort of garbage collector. There are different ways to handle this, maybe the easiest way is to use the session.gc_probability ( e.g. ini_set('session.gc_probability', 1) ) but I wrote a short command for my crontab to clear all the old ones that is older than 480 minutes ( 28800 seconds ).
0 * * * * find /var/www/websitefolder/phpSessionStorage -cmin +480 -type f -delete
As you can see, this cron job runs every hour and removes the old session files from the custom session folder.

So after all. My initial problem was never with a php-setting or apache but how Ubuntu-combined-with-php5 handles the garbage collector for the old php sessions.

Some tips when you'are having troubles with not getting the session.gc_maxlifetime to work.

  1. Are you allowed to change the session.gc_maxlifetime with ini_set() function? Check your permissions and your php.ini if the function is maybe disabled ( disable_functions ).
  2. All session settings must be declared before the session_start() function in your php-code. You can see if the session has been started with session_status() function.
  3. Check with ini_get() function if your configuration with ini_set() is really applied.
  4. What is wiping out the stored sessions if there are no configuration fault?
Read more about PHPs sessions configuration.