How to Delete session files using PHP

Post Reply
Tony
Lieutenant
Lieutenant
Posts: 86
Joined: Tue Jul 21, 2009 4:11 pm

How to Delete session files using PHP

Post by Tony » Sun Nov 29, 2009 4:40 am

If you are using a custom php.ini file to specify a user directory where session files are stored, this script can be used to delete old session files (the system will not purge them, so the directory will keep growing if you do not delete them). You must change the $sessionDir variable to the path where your session files are stored, and you can adjust the delete time frame as well (the example below uses 3 hours - you would not want to delete an active session). You can run this script directly or set it up to run at specific time intervals using cron.

Code: Select all

<?php
$sessionDir = "/home/user/temp/";  // your sessions directory
$compareTime = time() - 10800;  // 3 hours
$count = 0;
foreach (glob($sessionDir."*.sess") as $file)
  if ($compareTime >= filemtime($file))
    if (unlink($file)) $count++; 
echo "$count session files were deleted";
?>
Post Reply

Return to “PHP & MySQL”