PHP session management and temporary file cleanup

By default, PHP manages sessions during requests. This simplifies installation, because no cron job is required. To allow performance tuning, several configuration settings are allowed to adjust the frequency of the session cleanup checking and execution.

In the default php.ini, there is the following line:

cd /path/to/sessions; find -cmin +24 | xargs rm

Added as a cron job, this can be executed at set intervals (every one to five minutes is probably good), to clear the session file storage directory of files older than 24 minutes. Once implemented the find command can replace the default PHP session cleanup, so those configuration variables can be set to never check for session timeouts. This will speed PHP processing, although it may be imperceptible. It will also improve your control of session length, because the checking and clearing are executed based on time, not PHP requests.

Name any temporary files required to support the session with the session id, plus an extension to indicate the type and use. For example 4365kh2kj54dfg2kjh12.wav, 4365kh2kj54dfg2kjh12.rpt.txt, 4365kh2kj54dfg2kjh12.rpt.html. This allows a second session cleanup script to check for the presence of the session file based on the temporary file’s basename, and delete the temporary files. The second session cleanup script can be included in the main PHP script, or run as a separate cron job, unless the contents of the temporary files could be considered protected data, in which case they should be removed as soon as the session is terminated.

If authentication (logout) is also used to destroy sessions, a mechanism should be provided to clear any related, sensitive, files.