# Session Garbage Collection

> Section in “New and Extended Functionality › Session Management” of the book [PHP 7 Explained](https://php7explained.com/) by Sebastian Bergmann and Stefan Priebsch, published by thePHP.cc. The book covers PHP 7.0 to 7.4 and was last updated in November 2020. HTML version: <https://php7explained.com/new-and-extended-functionality/session-management/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:

``` php
#!/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.

---

Previous: [Session ID without Hashing](https://php7explained.com/new-and-extended-functionality/session-management/session-id-without-hashing/index.html.md) | Next: [I/O and Filesystem](https://php7explained.com/new-and-extended-functionality/io-and-filesystem/index.html.md)
