Aug 9, 2012

PHP :: session expires after inactivity

If you're getting frustrated why the session expires after 30 minutes, 1 hour of inactivity, you've probably already looked into the problem.

There are a few reasons why the session expires, so let's look at how session actually works.

On the server-side, PHP (usually / by default) stores session variables into files, usually in the /tmp folder.
The script sends a session cookie to the client, which expires after the session closes. At each request, the client sends the PHP session ID cookie back to the server, which uses this ID to access the session variables in the filesystem.
Now, so far we can understand that when the user closes the browser, the session cookie is removed and there is no way of accessing the session variables. The client has closed the session.

A setting in the php.ini file defines how long the session cookie should remain valid.


session.cookie_lifetime = 0

Setting the session.cookie_lifetime to 0 means that the session cookie is valid until the browser is closed. Setting it to something larger than 0 means that it remains valid for so many number of seconds.


Sometimes, however, the user is logged out of the session even though the browser has not been closed and the session cookie still exists. In this case, the server closed the session, meaning it deleted the files containing the session variables. This process is called garbage collection. Garbage collector in PHP deletes old session files that have a timestamp of last access time longer than the defined limit. The setting in php.ini for it is defined in seconds:

session.gc_maxlifetime = 1440

Session files older than 24 minutes [of inactivity] will be deleted. Changing the value to something like 1 week or a month can cause the session to be seemingly permanent. Some browsers have the option to never delete or reset session cookies even after browser restart (in chrome: continue where I left off), so you can achieve permanent sessions without implementing your own system to automatically restart the session via cookies or other types of local storage.

No comments: