2012-02-02 228 views
2

我正在尋找一個腳本來循環瀏覽一個文件夾,並刪除它裏面的所有文件,但最後一個,最近一個(我已經標記每個文件的名稱爲filename_date('Y')_date('m')_date('d').extension),不知道是否相關)。刪除文件夾內的所有文件,但刪除最後?

我已經在這裏發現了這個腳本的堆棧:

if ($handle = opendir('/path/to/your/folder')) 
{ 
    $files = array(); 
    while (false !== ($file = readdir($handle))) 
    { 
     if (!is_dir($file)) 
     { 
      // You'll want to check the return value here rather than just blindly adding to the array 
      $files[$file] = filemtime($file); 
     } 
    } 

    // Now sort by timestamp (just an integer) from oldest to newest 
    asort($files, SORT_NUMERIC); 

    // Loop over all but the 5 newest files and delete them 
    // Only need the array keys (filenames) since we don't care about timestamps now as the array will be in order 
    $files = array_keys($files); 
    for ($i = 0; $i < (count($files) - 5); $i++) 
    { 
     // You'll probably want to check the return value of this too 
     unlink($files[$i]); 
    } 
} 

這上面刪除任何東西,但在過去五年。這是做這件事的好方法嗎?還是有另一種方式,更簡單或更好?

回答

2

這是有效的。我不相信有一個更簡單的方法來做到這一點。另外,你的解決方案其實很簡單。

1

我認爲是一個很好的解決方案。只需修改循環

,但你可避免的循環排序的降序模式排列,所以你可以刪除所有陣列的節約只是第一個文件 編輯 排序從最新到舊的

0

我知道這是老休息但你也可以這樣做

$directory = array_diff(scandir(pathere), array('..', '.')); 
$files = []; 
foreach ($directory as $key => $file) { 
    $file = pathere.$file; 
    if (file_exists($file)) { 
     $name = end(explode('/', $file)); 
     $timestamp = preg_replace('/[^0-9]/', '', $name); 
     $files[$timestamp] = $file; 
    } 
} 
// unset last file 
unset($files[max(array_keys($files))]); 
// delete old files 
foreach ($files as $key => $dfiles) { 
    if (file_exists($dfiles)) { 
     unlink($dfiles); 
    } 
} 
相關問題