Session Garbage Collection

By default, PHP’s session extension keeps its data in individual session files on the filesystem. Depending on the amount of concurrently open sessions and the configuration in the php.ini file, these may be stored in one directory or multiple nested ones.

Given that a filesystem cannot clean up outdated session files by itself and no background processing can be assumed available – for instance because PHP is run as a module within the Apache web server –, PHP performs its own garbage collection at request time. While the probability of this happening can be adjusted by tuning the corresponding settings in php.ini, requests performing the garbage collection will be hit by a performance penalty. And the busier the server, the higher the performance impact. On the other hand, on low traffic websites the session files may remain on the filesystem longer than they should because no garbage collection was triggered.

To avoid these problems, it is recommended to simply disable runtime garbage collection by configuring session.gc_probability=0 and externally trigger a manual cleanup.

Starting with PHP 7.1, the new function session_gc() can be used to run PHP’s garbage collection process on demand, allowing for a very short script to cleanup expired sessions using a cron or comparable process scheduler:

#!/usr/bin/php
session_start();
session_gc();
session_destroy();

In case you wonder about the two other function calls: The session_start() is necessary to initialize session data storage access, and the session_destroy() is needed to explicitly destroy the session that was just started by calling session_start().

This background processing is of course only required if your session store is still filesystem based. Since most key-value stores like Redis or Memcached can expire keys based on a TTL, they can clean up outdated session entries automatically.