为foreach()提供的参数无效

时间:2012-07-07 20:05:11

标签: foreach php

下面的代码每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);
}

}
?>

1 个答案:

答案 0 :(得分:8)

由于glob()可能无法为空匹配(See "note" in Return section of the docs))可靠地返回一个空数组,因此您需要一个保护循环的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...';
}