2015-10-11 70 views
0

我在XAMPP文件夾結構刪除文件夾及其內容年長超過2天PHP

Deletefiles 
    --Uploads 
     --Test1 
     --Test2 
    --index.php 

的index.php我寫腳本來刪除上傳如測試1和測試2

$foldername = array('test1','test2'); 
function recursiveRemove($dir) { 
    $structure = glob(rtrim($dir, "/").'/*'); 
    if (is_array($structure)) { 
     foreach($structure as $file) { 

      if (is_dir($file)) recursiveRemove($file); 
      elseif (is_file($file)) unlink($file); 
     } 
    } 
    rmdir($dir); 
} 

foreach($foldername as $fname){ 
    recursiveRemove("uploads/".$fname."/"); 
} 
所有文件夾及其內容

其工作正常。但我想只刪除大於2天的文件夾。如何更改我的腳本。

+0

通過檢查文件日期 –

+0

我知道dagon.but我們如何能夠調用的文件recursiveremove功能僅超過2天以上。如果不是....年長 –

+0

看filemtime()和unlink文件http://php.net/manual/en/function.filemtime.php – Tom

回答

1

由於@Dagon指出您需要在刪除之前驗證文件對象的日期。

將此添加到您的foreach。該條件將詢問文件對象的日期是否小於當前時間減60秒* 60(分鐘)* 24(小時)* 2(天)。

foreach($structure as $file) { 
    if (filemtime($file) < time() - (60 * 60 * 24 * 2)) { 
     if (is_dir($file)) recursiveRemove($file); 
     elseif (is_file($file)) unlink($file); 
    } 
} 

請注意,您的遞歸函數不會刪除那些不符合條件的文件(它們是超過2天更新版本)裏面那些符合條件(年齡大於2天)的目錄。
製作rmdir如果不是空的,會發出警告。

+0

Okey..then其中t把命令rmdir($ DIR) –

+0

所有代碼保持不變 –

+0

它只能刪除文件ryt ...然後我怎麼能打電話rmdir刪除文件 –

0

你可以嘗試這樣的

function recursiveRemove($dir) { 
$structure = glob(rtrim($dir, "/").'/*'); 
if (is_array($structure)) { 
    foreach($structure as $file) { 

     if (is_dir($file)) { 
      recursiveRemove($file); 
     } elseif (is_file($file)) { 
      $lastmod = filemtime($file); 
      //48 hours in a day * 3600 seconds per hour 
      if((time() - $lastmod) > 48*3600) { 
      unlink($file); 
      } 
     } 
    } 
} 
$dirlastmod = filemtime($dir); 
if((time() - $dirlastmod) > 48*3600) { 
     rmdir($dir); 
    } 
} 

foreach($foldername as $fname){ 
recursiveRemove("uploads/".$fname."/"); 
} 
+0

它的唯一刪除文件不是我編輯的文件夾** $ foldername = array('test1','test2'); function recursiveRemove($ dir){ $ structure = glob(rtrim($ dir,「/").'/*'); \t $ cond = 0; 如果(is_array($結構)){ 的foreach($結構$文件){ \t \t \t如果(filemtime($文件)<時間() - (60 * 60 * 24 * 2)){ \t \t \t \t $ cond = 1; \t \t \t \t如果(is_dir($文件))recursiveRemove($文件); \t \t \t \t ELSEIF(is_file($文件))取消($文件); \t \t \t \t \t \t \t} } } 如果($ COND == 1){ \t命令rmdir($ DIR); \t \t } } 的foreach($文件夾名作爲$ FNAME){ \t \t \t recursiveRemove( 「上傳/".$ FNAME。」/「); \t} ** –

相關問題