Delete old PHP5 session files automatically
If not specified the PHP5 session files will be located in a directory like /var/lib/php5 and the builtin garbage collection will delete them, normally after 24 hours.
But often systems like CMS:es will put session files somewhere else and if the system doesn’t have it’s own garbage collection those session files will be kept forever. The reason can be to let a website visitor click “keep me logged in” or to remember a visitors preferences on the website. This normally doesn’t impose a problem as these session files are very small and the number of them counts in hundreds or possibly a couple of thousand files.
However, I encountered a site that created a very large number of session files and kept them forever. At some point the session files count was in the range of millions of files causing the system to run out of inodes. A solution could be to investigate how the system was handling session files but the internal workings of the site was outside of my responsibility. Another solution was to increase inodes but this will be a temporary solution.
The solution chosen was to create a garbage collection routine for the site in question, that deleted session files older than x days. The oldest session files was over 4 years old. The decision was to delete all session files older than a month (30 days), causing visitors who logged in, or had their preferences set, for more than a month ago had to re-login or set their preferences again on their next visit to the site. This was accomplished by the following command (which is run by cron every night):
find /var/www/somedomain.com/web/var/session/ -type f -mtime +30 -exec rm {} \;