3

下面的代码每 60 秒删除文件夹“Images”中的文件,它可以工作,但是当文件夹为空时,它会显示:警告:为 foreach() 提供的参数无效,如果没有文件,如何解决? " 文件夹为空而不是那个警告..

<?php
$expiretime=1; 

$tmpFolder="Images/";
$fileTypes="*.*";

foreach (glob($tmpFolder . $fileTypes) as $Filename) {

// Read file creation time
$FileCreationTime = filectime($Filename);

// Calculate file age in seconds
$FileAge = time() - $FileCreationTime;

// Is the file older than the given time span?
if ($FileAge > ($expiretime * 60)){

// Now do something with the olders files...

echo "The file $Filename is older than $expiretime minutes\r\n";

//delete files:
unlink($Filename);
}

}
?>
4

1 回答 1

8

由于 glob() 可能无法可靠地为空匹配返回一个空数组(请参阅文档的 Return 部分中的“note”),您只需要一个if保护循环的语句,如下所示:

$files = glob($tmpFolder . $fileTypes);
if (is_array($files) && count($files) > 0) {
    foreach($files as $Filename) {
        // Read file creation time
        $FileCreationTime = filectime($Filename);

        // Calculate file age in seconds
        $FileAge = time() - $FileCreationTime;

        // Is the file older than the given time span?
        if ($FileAge > ($expiretime * 60)){

        // Now do something with the olders files...

        echo "The file $Filename is older than $expiretime minutes\r\n";

        //delete files:
        unlink($Filename);
    }
} else {
    echo 'Your error here...';
}
于 2012-07-07T20:08:30.500 回答