Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP buffer ob_flush() vs. flush()

What's the difference between ob_flush() and flush() and why must I call both?

The ob_flush() reference says:

This function will send the contents of the output buffer (if any).

The flush() reference says:

Flushes the write buffers of PHP and whatever backend PHP is using (CGI, a web server, etc).

However, it continues to say:

[it] may not be able to override the buffering scheme of your web server…

So, seems to me that I could just use ob_flush() all of the time. However, I get strange results when I do that. Could someone explain in simple terms what's going on here?

like image 676
Ben Avatar asked Nov 16 '10 05:11

Ben


People also ask

What is flush () in PHP?

Definition and Usage. The flush() function requests the server to send its currently buffered output to the browser. The server configuration may not always allow this to happen.

What is the use of Ob_start () in PHP?

The ob_start() function creates an output buffer. A callback function can be passed in to do processing on the contents of the buffer before it gets flushed from the buffer. Flags can be used to permit or restrict what the buffer is able to do.

What is output buffering in PHP?

Output buffering is a mechanism for controlling how much output data (excluding headers and cookies) PHP should keep internally before pushing that data to the client. If your application's output exceeds this setting, PHP will send that data in chunks of roughly the size you specify.


2 Answers

ob_flush sends an application-initiated buffer. There may be multiple nested ob_start()'s in any PHP script. ob_flush passes the current content to the upper layer.

PHP itself might (at its own discretion) buffer output. This depends on the back-end. But usually FastCGI has a socket buffer on its own. Therefore flush() needs to be invoked as well to send the current content to the web server.

And now the web server might itself implement another buffering scheme (mod_deflate or content filter), which you have no influence over. But this is seldom, as it needs to be configured specifically.

Anyway, use both.

like image 166
mario Avatar answered Sep 19 '22 17:09

mario


ob_flush flushes output buffers you created with a function like ob_start

flush flushes buffered output of the PHP script itself to its caller

like image 36
Dan Grossman Avatar answered Sep 20 '22 17:09

Dan Grossman