php中的fgetc()feof()参数错误

时间:2017-04-04 07:15:23

标签: php file-io fgetc feof

今天我收到了来自我的网络服务器管理员的电子邮件,说“由于大约60 GB的错误文件,你的服务暂停。请通过FTP检查errorlog.txt。”在日志文件中,只有这两行重复:

[Tue Apr 04 08:45:52 2017] [error] [client xxx.xxx.xxx.xxx] PHP Warning:   feof() expects parameter 1 to be resource, boolean given in /var/www/vhosts/.../httpdocs/dene.php on line 11
[Tue Apr 04 08:45:52 2017] [error] [client xxx.xxx.xxx.xxx] PHP Warning:  fgetc() expects parameter 1 to be resource, boolean given in /var/www/vhosts/.../httpdocs/dene.php on line 13

以下是相关代码:

<?
header("X-XSS-Protection: 0");
$filename= $_GET['filename'];
$code = $_POST['code'];
if (isset($filename)) 
{
    $go = $filename;
    $full = "docs/$filename.htm";
    $filename = @fopen($full , 'r');
    $file_size = filesize($full);
    while (! feof($filename))  //line 11
    {
        $char = fgetc ($filename); //line13
        $code .= "$char";
    }
    fclose($filename);
}
    $code = str_replace("\\", "", $code);
$code = str_replace("&gt;", ">", $code);
$code = str_replace("&#61;", "=", $code);
$code = str_replace("&lt;", "<", $code);

printf("%s",$code);
?>

这是什么问题?提前谢谢......

2 个答案:

答案 0 :(得分:0)

您收到这些错误是因为您没有将有效资源作为feoffgetc中的参数传递。您应确保在以下位置传递有效的文件指针:

$filename = @fopen($full , 'r');

你应该确保:

  1. 您尝试打开的文件存在
  2. 它拥有正确的许可。 (如果需要,则为chmod 775)
  3. 如果其中一个失败,$ filename将返回false。您还可以改进代码逻辑来处理此错误情况,如下所示:

        $filename = @fopen( $full, 'r' );
    // Make sure we have a valid file resource
    if ( $filename ) {
        $file_size = filesize( $full );
        while ( ! feof( $filename ) )
        {
            $char = fgetc( $filename );
            $code .= "$char";
        }
        fclose( $filename );
    } else {
        // Not a valid file resource
        die( "This file resource could not be open." );
    }
    

    注意: $filename实际上不是正确的变量名称,您应将其重命名为$filePointer$fp

答案 1 :(得分:0)

您需要检查fopen结果。

$resource = @fopen($filename , 'r');
if ( $resource ) {
   while (! feof($resource))
   {
     ...
   }
}

来自php manual

<?php
// if file can not be read or doesn't exist fopen function returns  FALSE
$file = @fopen("no_such_file", "r");

// FALSE from fopen will issue warning and result in infinite loop here
while (!feof($file)) {
}

fclose($file);
?>