phpsession

cleanup php session files


On my website I use PHP sessions. Session information is stored in files in my ./session path. After a few months I discovered that these session files are never deleted, by now there are 145.000 of them in this directory.

How should these be cleaned up? Do I have to do it programmatically, or is ther a setting I can use somewhere that would have this cleanup happen automatically?

EDIT forgot to mention: This site runs at a provider, so I don't have access to a command line. I do have ftp-access, but the session files belong to another user (the one the webserver proces runs I guess) From the first answers I got I think it's not just a setting on the server or PHP, so I guess I'll have to implement something for it in PHP, and call that periodically from a browser (maybe from a cron job running on my own machine at home)


Solution

  • To handle session properly, take a look at http://php.net/manual/en/session.configuration.php.

    There you'll find these variables:

    These control the garbage collector (GC) probability of running with each page request.

    You could set those with ini_set() at the beginning of your script or .htaccess file so you get certainty to some extent they will get deleted sometime.

    IMPORTANT: (added by Elmü)

    To test if temporary session files are deleted you must meet several criteria:

    1. ini_set("session.gc_maxlifetime", "15"); will delete the session files after 15 seconds, but ONLY if the garbage collector is started which does not happen automatically after 15 seconds! Garbage collection is only started if the server receives a request AND probability and divisor are met.
    2. If you are testing this on a local XAMPP server without network traffic the session files will never be deleted. For testing set:
    3. ini_set("session.gc_probability", "1");
    4. ini_set("session.gc_divisor", "1");
    5. Then you must send a request to the server to start the garbage collector.
    6. In older PHP versions there was a bug, so session files were not deleted if you used session.save_path() to set another Temp directory. I tested this on PHP 8 where it works fine now.