Consent to the use of Personal Data and Cookies

This website needs your consent to use cookies in order to customize ads and content.

If you give us your consent, data may be shared with Google.

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.

1136 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. 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.
  2. How to effectively use variables within strings to insert bits of data where needed.
  3. Flushing and output buffering goes hand in hand, and in this article I try to examine the benefits and disadvantages to flushing.
  4. How to use the AVIF image format in PHP; A1 or AVIF is a new image format that offers better compression than WebP, JPEG and PNG, and that already works in Google Chrome.
  5. How to create a router in PHP to handle different request types, paths, and request parameters.

More in: PHP Tutorials