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

fgetc() feof() parameter error in php

今天我收到来自我的 Web 服务器管理员的电子邮件说 "your service is suspended due to about 60 GB error file. Check the errorlog.txt via FTP." 在日志文件中,只有这两行重复:

[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);
?>

这里有什么问题?提前致谢...

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

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

您应该确保:

  1. 您尝试打开的文件存在
  2. 并且它拥有正确的权限。 (如果需要,chmod 775)

如果上述之一失败,$filename 将 return 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

您需要检查 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);
?>