2011年11月30日水曜日

[PHP]ディレクトリの再帰削除処理

要件は以下の感じです。

サブフォルダを含めてファイル、ディレクトリを削除する。
ただし、ルートディレクトリは消したくないケースがある。
また、ファイルの最終更新日時が1日以上経ったものだけ削除する。


  1. function rmdirEx($rootPath , $dirDelete){  
  2.   
  3.  if( !is_dir($rootPath)) return;  
  4.   
  5.  $files = scandir($rootPath);  
  6.   
  7.  foreach($files as $file){  
  8.   if ($file == '.' || $file == '..'continue;  
  9.   $fullpath = $rootPath . DIRECTORY_SEPARATOR . $file;  
  10.   if(is_dir($fullpath)){  
  11.    rmdirEx($fullpath , true );  
  12.   }else{  
  13.    $lastUpdateTime = filemtime($fullpath);  
  14.    //更新日時が1日以上前のファイルのみ削除する  
  15.    if( ($lastUpdateTime + (60 * 60 * 24)) < time())  
  16.     @unlink($fullpath);  
  17.   }  
  18.  }  
  19.  //消せれば消す  
  20.  if$dirDelete) @rmdir($rootPath);  
  21.   
  22. }  

0 件のコメント: