为foreach提供的无效参数()
问题描述:
下面的代码每60秒删除文件夹“Images”内的文件,它可以工作,但是当文件夹为空时,它会显示:Warning:为foreach提供的无效参数() 这是固定的一样,如果没有文件,说“文件夹为空,而不是该警告..为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);
}
}
?>
答
由于水珠()可能无法可靠地返回一个空数组空匹配(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...';
}
现在我越来越:语法错误,意外T_ELSE – user1508409 2012-07-07 20:10:27
检查你的大括号...只要把你有什么,并包裹在这个如果块。 – 2012-07-07 20:13:49
ctrahey请问您可以在我已发布的代码中插入exmaple以向我展示它应如何放置?我马上就会知道 – user1508409 2012-07-07 20:14:50