Delete session files over time from creation

I save my sessions in a different directory from the / temp directory. let's say /session . (using session_save_path("session") )

there is also code to end the session after 10 minutes from the moment you create and log out.

but I mentioned that if a user logs in and, for example, closes his computer, my logout and session destroy the code domains that are not running, so the session file will remain in the session directory.

I wanted to know if there is a way to delete session files in /session some time after creation?

I used this code for it

  if ($handle = opendir('sessions')) { while (false !== ($file = readdir($handle))) { if (filectime($file)< (time()-600)) { // 600 = 10*60 unlink($file); } } } 

but without working, I think that he could not get the creation time of filectime($file)

thanks

+7
php session automation
source share
5 answers

thanks, but I think I can solve it myself

the decision was simple

  if ($handle = opendir('sessions')) { foreach (glob("sessions/sess_*") as $filename) { if (filemtime($filename) + 400 < time()) { @unlink($filename); } } } 
+4
source share

You do not need it. PHP itself implements a garbage collection mechanism to remove non-existent session files. This will be much more efficient than anything you could write with PHP.

See session.gc_ * configuration options for PHP for more details.

+4
source share

I did this earlier with a cron job that logged in and deleted session files older than X (for some reason, automatic PHP cleanup did not work). Unfortunately, this is probably not the option you need if it is on a managed node that does not allow you to create cron jobs.

+3
source share
 // Delete old sessions if (substr(ini_get('session.save_path'), 0, 4) != '/tmp') { foreach (glob(rtrim(ini_get('session.save_path'), '/') .'/sess_*') as $filename) { if (filemtime($filename) + ini_get('session.gc_maxlifetime') < time()) { @unlink($filename); } } } 
+1
source share
 // get the session files directory $dir = session_save_path("session"); //clear cache clearstatcache(); // Open a directory, and read its contents if (is_dir($dir)){ // we iterate through entire directory if ($dh = opendir($dir)){ while (($file = readdir($dh)) !== false){ //get the last acces date of each file @$time_stamp=fileatime($file); //check if it is older than... 600, and assign a text flag: with value "to delete" (when old enough) or "---" (when young enough) $to_delete = ($time_stamp<time()-600) ? 'to delete!' : '---'; //format acces date to a human readible format @$date = date("F d YH:i:s.",fileatime($file)); //output stats on the screen echo "file:" . $file . "Last access: ".$date.", ".$to_delete."<br>"; //INFO //depending on wishes, you can modify flow of the script using variables // particulary useful is $to_delete -> you can easily covert it to true/false format //to control the scrip } closedir($dh); } } 
0
source share

All Articles