PHP buffer ob_flush() vs. flush()
When you are streaming large responses or implementing real-time data feeds, simply printing to stdout isn't enough. You need to force the data out of the web server's memory and onto the wire immediately. This is where the confusion between ob_flush() and flush() usually arises. The documentation provides distinct definitions: ob_flush() sends the contents of the output buffer (if any), while flush() flushes the write buffers of PHP and whatever backend PHP is using, such as a CGI script or web server.
However, relying solely on ob_flush() often results in strange behavior where data appears delayed until the entire response has been generated. The reason lies in the architecture of how output buffering and HTTP headers interact within the PHP runtime.
The Role of Output Buffers
PHP does not send data to the client immediately every time you hit an echo statement or use print. Instead, it relies on output buffers (OPB). When a script starts, PHP checks if output buffering is enabled. If it is, the content you generate accumulates in memory until one of two things happens:
- The buffer reaches its maximum size limit.
- You explicitly call
flush(), which flushes the entire accumulated buffer to the client.
If your script has an active output buffer, calling ob_flush() tells PHP to push that specific buffered content to the next layer in the stack. However, this does not guarantee that the data reaches the physical network socket immediately. The underlying web server (like Apache or Nginx) or the CGI wrapper might still be holding its own internal buffers before passing the request to the client.
The Distinction Between ob_flush() and flush()
The critical difference is scope. ob_flush() operates strictly within the PHP output buffer layer. It ensures that whatever you have accumulated in PHP's memory has been handed off to the next handler. If no output buffering is active, ob_flush() effectively does nothing but consume a function call cycle.
flush(), on the other hand, operates at a lower level. It attempts to flush the write buffers of the underlying backend system. In a CGI environment or when running under specific web server configurations, this function forces the operating system and the web server to acknowledge that the data is ready to be sent over the network connection.
Why You Often Need Both
The reason you get strange results by using only ob_flush() is that PHP's internal buffer management and the web server's buffer management are separate entities.
If your script is generating content but no output buffer has been explicitly started (via output_buffering config or ob_start()), the data might be written directly to the stream, but the web server itself may still batch the write requests for performance reasons. Calling ob_flush() in this scenario does nothing because there is no PHP-level buffer to flush. Consequently, the data sits in the web server's buffer until it fills up or a timer expires.
By calling flush(), you bypass the PHP output buffer layer and force the backend to push whatever data has been collected so far to the network socket. To ensure immediate delivery of partial responsesâsuch as showing "50% complete" while a large file is being processedâyou typically need to:
- Clear any existing buffers.
- Output the current content.
- Flush the PHP buffer (
ob_flush()). - Flush the backend buffers (
flush()).
Implementation Considerations
Here is a pattern often used to ensure immediate delivery of partial output:
<?php
// Ensure no buffering is active before we start streaming
if (function_exists('ob_implicit_flush')) {
ob_implicit_flush(true);
} elseif (ini_get('output_buffering')) {
// If buffering is on, we might need to flush it off first
if (ob_get_length() > 0) {
ob_end_flush();
} else {
ob_flush();
}
}
// Output the chunk
echo "Processing data...";
// Flush PHP output buffer
ob_flush();
// Flush the web server/backend buffers
flush();
?>
It is important to note that flush() may not be able to override the buffering scheme of your web server if the server configuration explicitly disables flushing or uses a specific mod_deflate setup. In such cases, neither function will force data out until the buffer limits are met.
When Not to Force Flush
Forcing flushes every time you write to stdout can severely degrade performance. Modern web servers and PHP runtimes are optimized to batch writes. If you are rendering a standard HTML page where all content is known upfront, calling these functions adds unnecessary overhead and increases latency for users who do not need real-time updates.
The decision to use both functions should be driven by the requirement for partial content delivery (chunked transfer encoding) or the need to prevent large buffers from consuming excessive memory before sending data. If you are building a live dashboard or an automated report generator that needs to show progress, understanding the separation between PHP's buffer and the backend's buffer is essential for predictable behavior.