Saturday, July 17, 2010

A PHP script to delete files older than a spcecific time.

Okay here is the script written by me , to delete files older than a specific period (say 7 days).

Why i need this script ?
In the current project we need a system that seek and delete older files from FTP directory , older than 7 days .This script should run every week , will set a cron job for that which is not a issue here.

Well too much talking here is the code.

You are free to use/modify this code any way you want.But i am not responsible for any damage done by this code.

So use it only if u know how to use it :P

Any fixes/bugs/help please post in comments below .

<?php
set_time_limit(0);
//This class delets files n folder older than time specified
//Author :  Arshdeep Goswami <arshdeep79@gmail.com>

class DelOldfiles{
 var $older_than = NULL;
 var $total = 0;
 function __construct(){
  $this->older_than = mktime(date("H"),date("i"),date("s"),date("m"),date("d")-7,date("Y"));
 }
//Get all the files of the dir
 private function getAllfiles($dir){
  if(!is_dir($dir)) return false;
  $scaned = scandir($dir);
  array_shift($scaned);
  array_shift($scaned);
  $nsc = array();
  foreach($scaned as $sc)
   $nsc[] = "{$dir}/{$sc}";
  return $nsc;
 }
 
//Get size of the dir
 private function dirSize($directory) {
  $size = 0;
  foreach(new RecursiveIteratorIterator(new RecursiveDirectoryIterator($directory)) as $file){
   $size+=$file->getSize();
  }
  return $size;
 }
 
//Delete files recursively
 function delRecursive($dir){
  if(!is_dir($dir)) return false;
  $files = $this->getAllfiles($dir);
  if(empty($files)){
   return rmdir($dir);
  }  
  foreach($files as $key => $file){
   if(is_dir($file)){
    $this->delRecursive($file);
   }else if(file_exists($file)){
    unlink($file);
   }
  }
 //Once again calling after clearing file inside.
  return $this->delRecursive($dir);
 }
 
//Delete empty dirs
 function delEmptyDirs($dir){
  if(!is_dir($dir)) return false;
  $files = $this->getAllfiles($dir);
  $d_f = array();
  foreach($files as $key => $file){
   if(is_dir($file)){
    if($this->dirSize($file) > 0)
     $this->delEmptyDirs($file);
    else{
     $this->delRecursive($file);
    }
   }
  }
 }
 
 

//Call to delete every old file  
 public function del($dir){
  if(!is_dir($dir)) return false;
  $files = $this->getAllfiles($dir);
  $d_f = array();
  foreach($files as $key => $file){
   if(is_dir($file)){
    $this->del($file);
   }
   else if(file_exists($file)){
    $time = filemtime($file);
    if($this->older_than > $time){
     unlink($file);
     $total++;
    }
   }
  }
 } 
}


$obj = new DelOldfiles();
$f = $obj->del('D:\WINDOWS');
$f = $obj->delEmptyDirs('D:\WINDOWS');



No comments:

Post a Comment