PHP › Sessions & Cookies

How does PHP's session garbage collection work, and what settings control how long session data is kept before it is considered expired and eligible for cleanup?

Intermediate

Answer

PHP periodically runs a garbage collection process that removes session data files that have not been accessed within a configured maximum lifetime, controlled by the session.gc_maxlifetime setting, and since this cleanup process runs probabilistically based on session.gc_probability and session.gc_divisor rather than on every single request, on a low traffic site it is possible for expired session files to sit unused for longer than expected before they are actually cleaned up, which is worth considering when session storage space or expiration timing genuinely matters.
ini_set('session.gc_maxlifetime', 1800);
ini_set('session.gc_probability', 1);
ini_set('session.gc_divisor', 100);
Real-world example An application configures its session lifetime to thirty minutes of inactivity, automatically expiring a shopper's session and requiring them to log in again if they leave their browser open and inactive for longer than that configured window.

Common follow-ups: How can you manually force expired sessions to be cleaned up immediately rather than waiting for the probabilistic garbage collection?;What are the tradeoffs of storing session data in a database instead of the default file based storage?