How to flush output after each `echo` call?

How to flush output after each `echo` call?

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

How to flush output after each echo call?

Streaming data to a browser in real-time is a common requirement for log viewers, live dashboards, and long-running CLI tasks executed via web interfaces. The core issue described in your query stems from how the HTTP protocol handles response bodies and how PHP manages its internal buffers. When you use echo, the string isn't immediately sent over the network; it sits in an output buffer until that buffer is full or explicitly flushed.

If you've tried wrapping every echo statement with a manual flush or using ob_start() without success, it usually points to one of two specific constraints: browser-level buffering or server-side configuration blocking output buffering entirely.

The Browser Buffering Trap

Before adjusting your PHP code, you must address the client side. Modern browsers are designed to minimize network overhead by buffering incoming responses until they have a significant amount of data (often around 1024 bytes) before painting them to the screen. This is why your page appears blank even after sending kilobytes of logs; the browser is waiting for more data or a specific signal to render what it has received.

To force the browser to render data immediately, you must send a Cache-Control header and set an appropriate Content-Type. In PHP, this looks like:

header("Cache-Control: no-cache");
header("Pragma: no-cache");
header("Expires: 0");
header('Content-Type: text/plain'); // or your specific log format
?>
<?php
echo "Processing started...\n";
// Your processing logic here
?>

However, simply adding these headers rarely solves the issue if output_buffering is enabled on the server. You must explicitly tell PHP to flush the buffer after every write operation.

The Correct Approach: flush() vs. ob_flush()

There is a common misconception that ob_start() alone enables streaming. It merely starts capturing output into a buffer; it does not automatically send that buffer to the client on every write. To achieve true streaming, you need to interact with the output handler directly.

The standard and most reliable method is to call flush() immediately after your echo statement. While your source material notes that "it's dirty" to put a flush at the end of every echo, this is actually the correct semantic action for streaming. Without it, you are just accumulating data in memory without sending it anywhere.

Here is a robust pattern for streaming logs:

<?php
// Ensure no output has been sent before setting headers
if (ob_get_level() > 0) { ob_end_clean(); }

header("Cache-Control: no-cache");
header("Pragma: no-cache");
header('Content-Type: text/plain');

function streamLog(string $message): void {
    echo $message . "\n";
    flush(); // Critical: Forces the buffer to be sent immediately
}

streamLog("Step 1: Initialization");
// Simulate heavy processing
for ($i = 0; $i < 5; $i++) {
    sleep(2);
    streamLog("Processing batch " . ($i + 1));
}
?>

In this example, flush() ensures the buffer is emptied and sent to Apache/Nginx. If you are using a custom output handler or if ob_start() was called previously without a flush, the data remains trapped in that internal buffer until the script ends or the buffer fills up.

Server-Side Configuration Limitations

If implementing flush() alongside proper headers still results in no visible output, the bottleneck is likely your web server configuration. Apache and Nginx handle output buffering differently than PHP's internal handler.

For Apache:
Check if OutputBuffering is set to Off in your .htaccess or virtual host config. If it is disabled, PHP cannot flush buffers effectively. Conversely, if it is enabled but the server buffer size (LimitRequestBody or mod_deflate settings) is too small, the connection might hang. Ensure mod_headers is loaded to serve the Cache-Control headers correctly.

For Nginx:
Nginx has a default output buffer size defined in http { sendfile on; ... }. If your PHP script prints less than this threshold and doesn't flush, Nginx holds it. You may need to adjust fastcgi_buffer_size or disable buffering entirely for specific fastcgi_params if you require true byte-by-byte streaming, though this is rarely necessary for text logs.

Why Previous Attempts Failed

The source material mentions that ob_start() didn't work. This happens because ob_start() creates a new buffer but does not automatically flush it on every write. It only flushes when the script terminates or when ob_flush()/flush() is called. If you were relying on ob_start() to handle the flushing automatically, the data would sit in memory until the very end of the request, defeating the purpose of real-time logging.

Additionally, if your PHP environment runs under a shared hosting provider, they often disable output buffering by default or restrict access to low-level buffer controls for security reasons. In such environments, you might see ob_start() return false or ignore subsequent flush attempts. The most reliable check is to ensure no whitespace or BOM exists before the opening <?php tag, as any accidental echo breaks the ability to send headers required for streaming.

Ultimately, the "dirty" approach of flushing after every echo is the intended mechanism for this specific use case. It guarantees that the data leaves your application server and travels across the network incrementally, allowing the browser to update its display in real-time as long as your server and web server configurations allow it.

Our network