Cron & Session Files...

Small, short code snippets that other people may find useful. Do you have a good regex that you would like to share? Share it! Even better, the code can be commented on, and improved.

Moderator: General Moderators

Post Reply
evilMind
Forum Contributor
Posts: 145
Joined: Fri Sep 19, 2003 10:09 am
Location: Earth

Cron & Session Files...

Post by evilMind »

Cron is a wonderful tool :)
Use this about every hour (or half hour) to check for (and delete) session files over two hours old:

Code: Select all

<?php
   error_reporting  (E_ERROR | E_WARNING | E_PARSE);
   $session_files = array();
   $session_path = '/tmp';
   $dp = opendir($session_path);
   while (($contents = readdir($dp)) !== false) {
      if (!ereg("^\.",$contents) && ereg("^sess_",$contents)) {
         $session_files[] = $contents;
      }
   }
   if ( count($session_files) >= 1 ) {
      foreach ($session_files AS $gone_gone) {
      /* If the file was modified more than 2 hours ago, get rid of it.
         If not, it's probably pretty current so we'll keep it for a little while longer. */
         if ((filemtime( $session_path . '/' . $gone_gone) + (3600 * 2)) < time()) {
            unlink( $session_path . '/'.$gone_gone);
         }
      }
   }
?>
User avatar
m3mn0n
PHP Evangelist
Posts: 3548
Joined: Tue Aug 13, 2002 3:35 pm
Location: Calgary, Canada

Post by m3mn0n »

I recommend any cron file be blocked from access via a URL.

Here is an addition to that that would add more security for cron-scheduled php applications.

Code: Select all

<?php
if($REQUEST_URI) // URI = Uniform Resource Indicator (basically any requests via web browser)
{
    echo "You shouldn't be here!";   //error message
    exit; // so nothing more will load
} 
   else 
{
   error_reporting  (E_ERROR | E_WARNING | E_PARSE); 
   $session_files = array(); 
   $session_path = '/tmp'; 
   $dp = opendir($session_path); 
   while (($contents = readdir($dp)) !== false) { 
      if (!ereg("^\.",$contents) && ereg("^sess_",$contents)) { 
         $session_files[] = $contents; 
      } 
   } 
   if ( count($session_files) >= 1 ) { 
      foreach ($session_files AS $gone_gone) { 
      /* If the file was modified more than 2 hours ago, get rid of it. 
         If not, it's probably pretty current so we'll keep it for a little while longer. */ 
         if ((filemtime( $session_path . '/' . $gone_gone) + (3600 * 2)) < time()) { 
            unlink( $session_path . '/'.$gone_gone); 
         } 
      } 
   }
}
?>
Happy cron-ing
jason
Site Admin
Posts: 1767
Joined: Thu Apr 18, 2002 3:14 pm
Location: Montreal, CA
Contact:

Post by jason »

Or you could simply move the script out of the web directory, and into a directory not accessible from the outside. And simply use PHP via the command line.
Post Reply