我想檢查我的服務器上的文件夾是否每隔30分鐘超過一個小時,因此我設置了一個cronjob來執行此操作。由於我相當新的PHP,我不得不瀏覽一下,找到一個解決方案,不刪除我的父母/目標目錄,我找到了一個!不要刪除年齡小於1小時的文件
<?php
deleteContent("/var/www/html/downloads/");
function deleteContent($path){
try{
$iterator = new DirectoryIterator($path);
foreach ($iterator as $fileinfo) {
if($fileinfo->isDot())continue;
if($fileinfo->isDir()){
if(deleteContent($fileinfo->getPathname())){
if((time()-filectime($fileinfo->getPathname())) < 600)
{
@rmdir($fileinfo->getPathname());
}
}
}
if($fileinfo->isFile()){
if((time()-filectime($fileinfo->getPathname())) < 600)
{
@unlink($fileinfo->getPathname());
}
}
}
} catch (Exception $e){
// write log
return false;
}
return true;
}
?>
注意,if((time()-filectime($fileinfo->getPathname())) < 600)
是我找到解決我的時間問題的辦法。
該腳本不應該刪除小於1小時的文件夾或文件,所以我花了我們現在的時間,並減去了該文件/文件夾上次更改的時間,並將其與600秒( 10分鐘)僅用於測試目的。
不幸的是,腳本仍然會刪除每個文件,而不管它何時創建。
我做錯了什麼或有沒有人有另一種方法?
感謝
打印time()和filectim e($ fileinfo-> getPathname()函數並檢出它們。 – Naga