Search code examples
phpfile-iofgetcfeof

fgetc() feof() parameter error in php


Today I've got email from my web server admin says that "your service is suspended due to about 60 GB error file. Check the errorlog.txt via FTP." In log file, there are only these two lines repeteadly:

[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

And here is the relative code piece:

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

What is the problem here? Thanks in advance...


Solution

  • You need check the fopen result.

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

    from the 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);
    ?>