我正在尋找一個腳本來循環瀏覽一個文件夾,並刪除它裏面的所有文件,但最後一個,最近一個(我已經標記每個文件的名稱爲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]);
}
}
這上面刪除任何東西,但在過去五年。這是做這件事的好方法嗎?還是有另一種方式,更簡單或更好?