automatic file deletion

Discussion in 'PHP' started by cavendano, Oct 9, 2007.

  1. #1
    need a helping hand here...in this php file the script will automatically delete all files older than the time I set....the only thing is that I would want it to delete everything except an .htaccess file I have in there...
    another thing i would want it to do is go into three seperate folders to delete the items...not subdirectories within that first one...

    <?php
    function delete_old_files($dir, $time_limit = 0){
     if(!$time_limit) $time_limit = 1*24*60*60;
     if ($df = opendir($dir)) {
      while (false !== ($file = readdir($df))) {
       if ($file != "." && $file != "..") {
        $last_modified = filemtime($file);
        if(time()-$last_modified > $time_limit){
         unlink($file);
        }
       }
      }
      closedir($df);
     }
    }
    
    delete_old_files('.');
    
    ?>
    PHP:
     
    cavendano, Oct 9, 2007 IP
  2. sabmalik

    sabmalik Peon

    Messages:
    33
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #2
    umm i think the htaccess part if pretty simple , you can create a third parameter for that function. and to delete from three seperate folders, call the function 3 times i reckon!

    something like this

    
    function delete_old_files($dir, $time_limit = 0,$exclude=array()){
     if(!$time_limit) $time_limit = 1*24*60*60;
     if ($df = opendir($dir)) {
      while (false !== ($file = readdir($df))) {
       if ($file != "." && $file != "..") {
        $last_modified = filemtime($file);
    	
        if((time()-$last_modified > $time_limit) && !in_array($file , $exclude)){
         unlink($dir."/".$file);
        }
       }
      }
      closedir($df);
     }
    }
    
    delete_old_files('folder1' , 10 , array('.htaccess'));
    delete_old_files('folder2' );
    delete_old_files('folder3' );
    
    PHP:
     
    sabmalik, Oct 9, 2007 IP
  3. cavendano

    cavendano Well-Known Member

    Messages:
    360
    Likes Received:
    9
    Best Answers:
    0
    Trophy Points:
    130
    #3
    am i missing something? it seems as if though everytime I run it all files get deleted including recent ones...
     
    cavendano, Oct 9, 2007 IP