Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explanation of PHP's fflush() function

The manual says that it flushes the output to a file. Plus they give an example.

$filename = 'bar.txt';

$file = fopen($filename, 'r+');
rewind($file);
fwrite($file, 'Foo');
fflush($file);
ftruncate($file, ftell($file));
fclose($file);

I tried to understand its necessity. What I did was the following:

  • I created a bar.txt file
  • I runned the script
  • I opened bar.txt and saw 'Foo' inside it, then I made the file empty again.
  • Then... I removed fflush($file); from the script and runned it again.
  • The result was exactly the same. I made the file empty yet another time.
  • After that I changed the frwite() line to fwrite($file, 'Foo'); die();
  • Again... same results... a file with 'Foo' inside it.

Now, I don't see the point of using fflush().

I can't see the necessity of fflush in this example. Can you provide an example in which fflush() is really necessary.

Link: http://php.net/manual/en/function.fflush.php

like image 770
Julian S Avatar asked May 09 '16 15:05

Julian S


1 Answers

fflush

For efficiency purpose, core system library of PHP does not necessarily writes to a file immediately when we call functions like fwrite or fputcsv. It stores them in buffer and stores at the same time after a while.

For eg lets say you have loop and inside that loop you call fputcsv function then system library of PHP does not necessarily stores it into the file at every loop.

So whats the point of using fflush?

But for logging purpose we need to ensure that log is seen as soon as possible therefore it is better to use fflush after each fwrite. For other purpose than logging we don't need to force flushing. Let PHP internals handle the efficiency.

Reference

This function forces a write of all buffered output to the resource pointed to by the file handle. fflush PHP Documentaiton

like image 110
Bikal Basnet Avatar answered Sep 28 '22 08:09

Bikal Basnet