2
我已成功使用此腳本刪除單個指定目錄中比一天早的所有圖像。刪除多於1天的多個目錄中的所有圖像
但是我需要這種治療多種圖像文件夾。雖然我可以複製刪除腳本,但我寧願保留在一個腳本中。
所有圖像文件夾都是主文件夾的子文件夾,所以理想情況下我會遞歸地查找指定路徑的所有子文件夾中比一天早的所有圖像。
<?php
$days = 1;
$path = '/home/boston64/public_html/webcams/';
$filetypes_to_delete = array("jpg");
// Open the directory
if ($handle = opendir($path))
{
// Loop through the directory
while (false !== ($file = readdir($handle)))
{
// Check the file we're doing is actually a file
if (is_file($path.$file))
{
$file_info = pathinfo($path.$file);
if (isset($file_info['extension']) && in_array(strtolower($file_info['extension']), $filetypes_to_delete))
{
// Check if the file is older than X days old
if (filemtime($path.$file) < (time() - ($days * 24 * 60 * 60)))
{
// Do the deletion
unlink($path.$file);
}
}
}
}
}?>
謝謝!我會試一試 - 爲了我自己的教育:我遇到了麻煩,哪個代碼段處理遞歸檢查子文件夾? –
它沒有經過測試,所以是的,強調「嘗試」!所以你可以看到我定義了一個名爲'deleteOldImages(...)'的函數。在該函數內部,它循環遍歷目錄中的所有內容,如果該目錄是目錄,則該函數會在該子目錄上自動調用(遞歸)。顯然,對於該子目錄中的每一件事情,如果有更多的目錄,該函數將在TH子子目錄上自我調用(遞歸),依此類推。 – Luke
(分裂註釋對不起)遞歸是從最後一行代碼實際調用該函數開始的,並且您可以看到它將在以深度優先方式考慮文件系統樹中的每個元素時結束。 – Luke