問題描述
只是好奇
$files = glob(cacheme_directory()."*");
foreach($files as $file)
{
$filemtime=filemtime ($file);
if (time()-$filemtime>= 172800)
{
unlink($file);
}
}
我只想確定代碼是否正確.謝謝.
I just want to make sure if the code is correct or not. Thanks.
推薦答案
你應(yīng)該添加一個(gè) is_file()
檢查,因?yàn)?PHP 通常會(huì)列出 .
和 ..
,以及可能駐留在您正在檢查的目錄中的子目錄.
You should add an is_file()
check, because PHP normally lists .
and ..
, as well as sub-directories that could reside in the the directory you're checking.
此外,正如此答案所建議的,您應(yīng)該用更具表現(xiàn)力的符號(hào)替換預(yù)先計(jì)算的秒數(shù).>
Also, as this answer suggests, you should replace the pre-calculated seconds with a more expressive notation.
<?php
$files = glob(cacheme_directory()."*");
$now = time();
foreach ($files as $file) {
if (is_file($file)) {
if ($now - filemtime($file) >= 60 * 60 * 24 * 2) { // 2 days
unlink($file);
}
}
}
?>
或者,您也可以使用 DirectoryIterator
、如本答案所示.在這種簡單的情況下,它并沒有真正提供任何優(yōu)勢,但它會(huì)是 OOP 方式.
Alternatively you could also use the DirectoryIterator
, as shown in this answer. In this simple case it doesn't really offer any advantages, but it would be OOP way.
這篇關(guān)于在PHP中刪除所有超過2天的文件的正確方法的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!