1

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...

WhoCares
  • 225
  • 1
  • 5
  • 16
  • 1
    [*"`fopen`: Returns a file pointer resource on success, __or FALSE on error__."*](http://php.net/manual/en/function.fopen.php#refsect1-function.fopen-returnvalues) – user3942918 Apr 04 '17 at 07:18

2 Answers2

0

You are getting these errors because you are not passing a valid resource as parameter in feof and fgetc. You should make sure you are passing a valid file pointer in:

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

You should make sure:

  1. The file you are trying to open exists
  2. And it has the correct permission. (chmod 775 if needed)

if one of above fails, $filename will return false. You can also improve the code logic to handle this error condition as follows:

    $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." );
}

Note: $filename is not actually the correct variable name, you should rename it to $filePointer or $fp

Hyder B.
  • 10,900
  • 5
  • 51
  • 60
0

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);
?>
Alisher Gafurov
  • 449
  • 5
  • 15