Share via:

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.

42 views

Edited: 2020-01-05 13:59

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.

Comments