php 警告 fclose() 期望参数 1 为给定的资源布尔值

Key*_*sho 5 php file-io warnings

我使用 newrelic 来跟踪我网站上的所有内容,但总是收到此错误:

错误消息:E_WARNING:fclose()期望参数 1 为资源,给定布尔值堆栈跟踪:在 /etc/snmp/bfd-stats.php 调用的 fclose 中(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");

?>
Run Code Online (Sandbox Code Playgroud)

第40行:$fh = fopen('/var/log/bfd_log', 'r');我查看了目录/var/log,没有名为 的文件bfd_log,我不知道是否需要自己创建它还是自动创建的。

任何人都可以帮我解决这个错误,提前致谢。

ins*_*ns0 4

该错误表明您正在尝试将带有布尔值(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   
    }
}
Run Code Online (Sandbox Code Playgroud)

如果您在使用变量之前始终进行检查,则不会再遇到此错误。