PHP: Fread in a Loop is Dangerous

The fread function can be dangerous when used inside a loop in PHP, find out how to secure it in this article.

1283 views
d

By. Jacob

Edited: 2021-02-07 23:09

I recently had to fix a problem caused by calling PHP fread inside a while loop. The problem was not so much that I used fread inside a loop, but more that I had an unrelated unhandled error caused by incorrect file permissions.

Long story short, the error meant that fread would fail catastrophically by causing an error message to be written to the Apache error log file—filling out the entire hard drive space in a matter of seconds!

The specific error message was:

Length parameter must be greater than 0

Of course this problem is not just unique to using the fread function. It is just that the specific use of the function made it more likely to happen.

This is just another reason not to use the file- functions of PHP directly. There is simply too many things that can go wrong, even with a fairly good understanding of the functions.

I secured the use of fread against running amok by suppressing errors using the at (@) character. This is one of the only times I recommend suppressing errors:

$buffer = $this->f_args['chunk_size'];
while (!feof($fp) && ($pointer = ftell($fp)) <= $end) {

  // If next $buffer will pass $end,
  // calculate remaining size
  if ($pointer + $buffer > $end) {
    $buffer = $end - $pointer + 1;
  }

  echo @fread($fp, $buffer);
  flush();
}
fclose($fp);
exit();

Check out Beamtic's File Handler library for a full example of implementation.

Tell us what you think:

  1. In this Tutorial, it is shown how to redirect all HTTP requests to a index.php file using htaccess or Apache configuration files.
  2. How to create a router in PHP to handle different request types, paths, and request parameters.
  3. Tutorial on how to use proxy servers with cURL and PHP
  4. When using file_get_contents to perform HTTP requests, the server response headers is stored in a reserved variable after each successful request; we can iterate over this when we need to access individual response headers.
  5. How to effectively use variables within strings to insert bits of data where needed.

More in: PHP Tutorials