gpt4 book ai didi

foreach - 为 foreach() 提供的参数无效

转载 作者:可可西里 更新时间:2023-11-01 00:15:45 31 4
gpt4 key购买 nike

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

}
?>

最佳答案

由于 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...';
}

关于foreach - 为 foreach() 提供的参数无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11378251/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com