我使用newrelic来跟踪我网站上的任何内容,我总是得到这个错误:
错误消息:E_WARNING: fclose()期望参数1是给定的资源布尔值/etc/snmp/bfd-stats.php (68)
这是/etc/snmp/bfd-stats.php
的样子
<?php
$a = 0;
$ptr = 0;
$any = 0;
$mx = 0;
$ns = 0;
$cname = 0;
$soa = 0;
$srv = 0;
$aaaa = 0;
$txt = 0;
$total = 0;
if(file_exists('/etc/snmp/bfd-log-pos.stat')) {
$lfh = fopen('/etc/snmp/bfd-log-pos.stat','r');
$string = fread($lfh,2087);
$res = explode(',',$string);
fclose($lfh);
}
else {
$res = array();
$res[0] = 0;
$res[1] = 0;
}
if(file_exists("/var/log/bfd_log.1")) {
$stats = stat('/var/log/bfd_log.1');
if($stats[10] > $res[0]) {
$res[0] = 0;
$res[1] = 0;
}
}
$fh = fopen('/var/log/bfd_log', 'r');
fseek($fh,$res[1]);
$blocks = 0;
if(!$fh) {
echo "Error! Couldn't open the file.";
} else {
while (!feof($fh)) {
$data = fgets($fh);
if(preg_match('/executed'sban/',$data)) {
$blocks++;
}
}
}
$lfh = fopen('/etc/snmp/bfd-log-pos.stat','w');
$timestamp = time();
$pos = ftell($fh);
fwrite($lfh,"$timestamp,$pos");
fclose($lfh);
if(!fclose($fh)) {
echo "Error! Couldn't close the file.";
}
print("bfd_blocks'n$blocks");
?>
在第40行:$fh = fopen('/var/log/bfd_log', 'r');
上,我查看了目录/var/log
,没有名为bfd_log
的文件,我不知道是我自己创建的还是自动创建的。
谁能帮我修复这个错误,提前谢谢。
该错误表明您正在尝试将具有布尔值(true/false)的变量传递给需要资源而不是布尔值的函数。
请确保在使用来自变量的资源之前,返回该资源的函数没有遇到问题。只有在成功执行使用此资源/变量的其他函数时才执行。
$fh = fopen('/var/log/bfd_log', 'r');
// check fh before other functions use this variable
if (!$fh) {
echo "Error! Couldn't open the file.";
} else {
// perform task with resource $fh
fseek($fh, $res[1]);
[...]
$lfh = fopen('/etc/snmp/bfd-log-pos.stat', 'w');
// check before other code block is executed and use this variable
if( $lfh )
{
// perform task with resource $lfh
$pos = ftell($fh);
fwrite($lfh, "$timestamp,$pos");
fclose($lfh);
fclose($fh);
[...]
} else {
// lfh error
}
}
如果你总是在使用变量之前检查,你就不会再遇到这个错误了
我一直在纠结这个问题,直到我把写检查(放在第一位)和实际的文件写代码分开,我才找到答案。因此,在我打开文件fopen/fwrite之前,然后执行is_writable检查,然后执行fclose,我会得到这个错误。
为了解决这个问题,我在fopen/fwrite之前移动了is_writable和variable声明,错误就消失了。如下所示(以前的php代码位置显示在注释中)第一个注释确实帮助我认识到这一点…谢谢你。
$myfile = "/var/www/html/newfile.txt";
if (is_writable($myfile)) {
echo "The file is writable";
}
else {
echo "The file is not writable";
}
$txt = "$name, $email, $command, $searchtype, $keyword 'n";
$myfile = fopen('/var/www/html/newfile.txt', 'w') or die("Unable to open file!");
fwrite($myfile, $txt);
// $myfile = "/var/www/html/newfile.txt";
// if (is_writable($myfile)) {
// echo "The file is writable";
// }
// else {
// echo "The file is not writable";
// }
fclose($myfile);
Try
$fh = fopen('/var/log/bfd_log', 'a+');
a+模式将在文件不存在的情况下创建该文件