[英]Do not delete files that are younger than 1 hour
我想每 30 分鍾檢查一次服務器上的文件夾中是否有超過一小時的文件,因此我設置了一個 cronjob 來執行此操作。 由於我對 php 還很陌生,我不得不瀏覽一下才能找到一個不會刪除我的父/目標目錄的解決方案,我找到了一個!
<?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 分鍾)進行比較用於測試目的。
遺憾的是,無論文件何時創建,腳本仍然會刪除每個文件。
我做錯了什么還是有人有其他方法?
謝謝
有時調用底層操作系統的函數是更好的方法
exec('find /var/www/html/downloads/ -type f -mmin +60 -exec rm {} \;');
執行: http : //php.net/manual/en/function.exec.php
php 函數來運行 cli 命令 find,它會在指定的路徑中查找文件時間大於 60 分鍾的 f(for file) 類型的文件,然后 exec(run) rm 是 linux remove(delete)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.