Are PHP session files ever deleted?

They should be deleted by the PHP garbage collector. The frequency is controlled by the session.gc_maxlifetime setting in php.ini. Possibly if this is not kicking in you have other problems.


On default Debian and Ubuntu, the sessions are cleaned up by cron /etc/cron.d/php5

# Look for and purge old sessions every 30 minutes
09,39 *     * * *     root   [ -x /usr/lib/php5/maxlifetime ] && [ -d /var/lib/php5 ] && find /var/lib/php5/ -type f -cmin +$(/usr/lib/php5/maxlifetime) -delete

where /usr/lib/php5/maxlifetime gives lifetime in minutes as set in session.gc_maxlifetime.


Also at reboot - as /tmp is always cleared out on reboot.


You could setup a cron script to clean them up automatically. It's generally a good idea to test for creation date older than what the life of cookies is set up to be on your system.

Limiting cookie life is done thusly (must be done before script outputs anything):

<?php
session_name('my_site_name');
session_set_cookie_params(1209600); # max cookie age of 14 days
# send cookie headers
session_start();
?>

Then, in your cleanup script:

#!/bin/sh
find /tmp -maxdepth 1 -type f -name 'php_session_file_prefix*' -ctime +15 -exec rm -f {} \;

Then, in your crontab:

# Run daily cron jobs at 03:40 every day
40 3 * * * /path/to/php-session-cleanup.sh