I have had precisely the same issue. My solution was to check for the session file:
<?php
// clean-up script. Get cron/windows task scheduler to run this every hour or so
// this is the path where PHP saves session files
$session_path = ini_get('session.save_path');
// this is the directory where you have created your folders that named after the session_id:
$session_files_dir = '/path/to/your/save/dir';
// loop through all sub-directories in the above folder to get all session ids with saved files:
if ($handle = opendir($session_files_dir)) {
while (false !== ($file = readdir($handle))) {
// ignore the pseudo-entries:
if ($file != '.' && $file != '..') {
// check whether php has cleaned up the session file
if ( file_exists("$session_path/sess_$file") ) {
// session is still alive
} else {
// session has expired
// do your own garbage collection here
}
}
}
closedir($handle);
}
?>
Note that this assumes that the session.save_handler
ini setting is set to "files"
, the session.save_path
setting does not have the directory-level prefix (i.e. does not match regex /^\d+;/
) and that php's automatic session garbage collection is enabled. If either of the above assumptions are not true then you should be implementing manual session garbage collection anyway, so can add your clean-up code to that.
This also assumes that the only files in $session_files_dir
are your per-session folders and they are all named after their associated session_id.