Sunday, January 23, 2011

Are PHP session files ever deleted?

I see there are thousands of files in my "/tmp" directory (a CentOS machine) and almost all of them are PHP session files.
I'm worried about the possible impact this might have on my system.
Are those files ever deleted either by the OS, Apache or PHP? or I have to take care of it myself?

  • 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.

    See here for a nice write up.

    GetFree : But garbage collection exits from PHP 5.3 on. What about older versions?
  • 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 -type f -maxdepth 1 -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
    

0 comments:

Post a Comment