How To: Increase Session Time for PHP and Apache

by Stephen Fluin 2011.01.03

Session management in PHP is one of its greatest strengths. The only downside of its session management is in the expiration period for sessions. By default in Ubuntu the timeout is set to about 24 minutes, which is fine for most situations. When doing article editing or other things that can take more than 24 minutes, however, it's frustrating to submit a form and have a session expiry lose the data you have been working on.

One way to overcome the time limit is to have regular automatic saves done via AJAX, but another technique is to increase the session time. In order to change the session timeout, the change needs to be made in the PHP configuration. In some distributions, this file is stored in /etc/php.ini. In Ubuntu and some other distributions, this file is stored in /etc/php5/apache2/php.ini. This setting is controlled by session.gc_maxlifetime. What this setting does is to control the session cleanup. After making any changes to this setting in the php.ini, make sure you restart apache to ensure that the version of PHP being used by Apache is updated with your configuration changes.

In PHP, sessions are probabilistically erased at regular intervals after gc_maxlifetime. By changing this max lifetime, you increase the time for which the session will be valid. You could also make changes to the divisor or probability of cleanup, but I have found that these settings can simply be left to their original values without negatively affecting the functioning of the sessions.


permalink