automatix
automatix

Reputation: 14552

How to configure PHP for automatical regular removing of session data / sess_ files?

The PHP session data is stored on the server side in sess_{$hash} files in the directory defined in the session.save_path setting of php.ini.

If my understanding is correct, these files should get removed after a defined period of time. How to get and how to set this time? I tried settings session.cache_expire and session.gc_maxlifetime. E.g. I set session.cache_expire to 2 (minutes), but after two minutes the files are still there. I also set session.gc_maxlifetime to 120 (seconds). But this also didn't work.

How to configure PHP to get the sess_* files being removed after a defined period of time?

Upvotes: 0

Views: 115

Answers (1)

Sherif
Sherif

Reputation: 11942

The session.gc_maxlifetime is what defines when sessions data is marked for garbage collection (not necessarily when it's deleted). The actual deletion of that data depends on a number of variables. Most prominently the session.gc_probability and session.gc_divisor. The probability over the divisor determine the chance that the session initialization process will invoke the garbage collector to clean up marked garbage. By default they are 1 and 100, respectively (meaning there is a 1% chance the garbage collector will clean up).

This is PHP's default mechanism for garabage collection of session data. However, on some systems (most notably Ubuntu) the default session GC is replaced by an external cleanup mechanism which is implemented as a cron job that runs regularly to clean up session files based on stat calls and the session.gc_maxlifetime.

You tend not to notice these side effects on a busy site, as the number of session_start() calls increase, the probability that stale session data is regularly cleaned up increases. However, on a low traffic site (namely your development environment) this probability drops significantly enough that you might notice stale session data hanging around for a while. This is typically not something to be concerned with. As long as you are deleting the session cookie and regularly using session_destroy() when the session needs to be deleted, this is all moot.

Upvotes: 2

Related Questions