Flushing System Buffers
PHP provides two related ways to flush (send and discard the contents of) system buffers: through calling flush() and through enabling implicit flushing with ob_implicit_flush() or the implicit_flush php.ini setting.
Output Flushing Behaviour
With implicit flushing disabled, PHP will flush output only when flush() is called or when the script ends.
With implicit flushing enabled, PHP will attempt to flush after every block of code resulting in output. Output in this context is non-zero length data that is:
- outside of the
<?php ?>tags - printed by language constructs and functions whose explicit purpose is to output user provided variables or strings such as echo, print, printf(), var_dump(), var_export(), vprintf()
- printed by functions whose purpose is to collect and output data/information on the running script or PHP such as debug_print_backtrace(), phpcredits(), phpinfo(), ReflectionExtension::info()
- printed by PHP on an uncaught exception or an unhandled error (subject to the settings of display_errors and error_reporting)
- anything written to
php://output
Note: Printing empty strings or sending headers is not considered output and will not result in a flush operation.
If implicit flushing is enabled, control characters (e.g. "\n", "\r", "\0") will trigger flushing as well.
Limitations
This functionality cannot flush user-level output buffers. To use these together, user-level output buffers must be flushed before flushing system buffers in order for PHP to produce any output.
Calling flush() or implicit flushing being enabled can interfere with output handlers of user-level output buffers that set and send headers in a web context (e.g. ob_gzhandler()) by sending headers before these handlers can do so.
Buffering implemented by the underlying software/hardware cannot be overridden by PHP and should be taken into account when working with PHP's buffer control functions. Checking the web servers/browsers/consoles buffering settings and working with these can alleviate possible issues. Working in a web context, either the web server's buffering settings or the script's buffering could be adjusted to work in tandem whereas working around the buffering strategies of various browsers can be achieved by adjusting buffering in the PHP script. On consoles that implement line buffering, newline characters could be inserted in the appropriate places before flushing output.
SAPI Differences In Flushing
Although flushing is implemented by each SAPI in a slightly different way, these implementations fall in one of two categories:
- SAPIs used in a web context will flush headers first followed by the output.
Apache2Handler,CGI,FastCGIandFPMare such SAPIs - other SAPIs such as
CLIandembedwill flush output only