How to disable output buffering in PHP

How to disable output buffering in PHP

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

Stefan Bogdanescu

Founder & Senior Architect

How to Disable Output Buffering in PHP

Streaming live video feeds from a camera to a browser requires precise control over how data is delivered. When dealing with MJPEG streams or real-time sockets, the default behavior of PHP often works against you by accumulating data in memory before sending it to the client. This accumulation creates latency and causes the "freeze" effect observed when streaming low-bandwidth sources like 1 FPS cameras.

The core issue lies in PHP's output buffering mechanism. By default, PHP collects output—whether from echo, print, or function returns—and flushes it only when a specific threshold is reached or when the script finishes. In your specific scenario, where you are reading chunks of MJPG data via fread and immediately printing them, this buffer fills up quickly with large resolution frames but slowly with small ones. Once the buffer hits its internal limit, PHP dumps all accumulated content at once, resulting in a sudden burst of frames after a long delay.

To resolve this, you must explicitly instruct PHP to flush output immediately after every write operation and disable the buffering layer entirely.

Disabling Output Buffers Programmatically

The most reliable way to ensure immediate output is using ob_implicit_flush(true) combined with ini_set('output_buffering', 'off'). The code snippet you provided attempts this logic but mixes several approaches that can lead to confusion or incomplete flushing. Specifically, manually calling ob_end_flush() inside a loop is unnecessary if the buffer level is low; PHP handles stack management automatically when implicit flush is enabled.

Here is the corrected approach for your relay script:

ignore_user_abort(false);
set_time_limit(0);

$socketConn = @fsockopen("192.168.1.6", 1989, $errno, $errstr, 2);
if (!$socketConn) {
    exit();
}

stream_set_timeout($socketConn, 10);
fputs($socketConn, "GET /mjpeg HTTP/1.0\r\n\r\n");

// Setup Header Information
header("Cache-Control: no-cache");
header("Cache-Control: private");
header("Pragma: no-cache");
header("Content-type: multipart/x-mixed-replace; boundary=myboundary");

// CRITICAL: Disable buffering immediately
ini_set('output_buffering', 'off');
ob_implicit_flush(true);
@ini_set('implicit_flush', 1); // Redundant if implicit_flush is true, but harmless

stream_set_blocking($socketConn, false); // Ensure non-blocking read

while (connection_status() == CONNECTION_NORMAL) {
    $chunk = fread($socketConn, 128);
    
    // Only print if data was actually received to avoid printing empty strings
    if ($chunk !== false && strlen($chunk) > 0) {
        echo $chunk; 
    }
}

fclose($socketConn);

Why This Works

By setting output_buffering to 'off', you tell the PHP engine not to maintain a buffer for output. Every call to echo or print goes directly to the network stream. The subsequent ob_implicit_flush(true) ensures that even if any buffering logic were re-enabled by other parts of your application, the flush happens automatically after every print statement.

Important Pitfalls and Trade-offs

Disabling output buffering is not without risks in a production environment. If you are building standard web pages with HTML forms or AJAX requests, disabling the buffer can cause issues because PHP might expect to see headers before any body content. However, for a raw stream relay like this, it is the correct choice.

A common mistake is forgetting to clear existing buffers before turning off buffering. In your original code, you called ob_end_flush() inside a loop over ob_get_level(). While this clears stacked buffers, it does not necessarily disable the underlying output buffer if it was initialized at the start of the script. The combination of ini_set('output_buffering', 'off') and ob_implicit_flush(true) is generally safer and cleaner than trying to manually dismantle the stack.

Another consideration is the fread call. Reading in chunks (e.g., 128 bytes) is good, but ensure you are handling empty reads correctly. In a streaming scenario, reading zero bytes often indicates the end of the stream or a network timeout, not data to be printed. Always check if $chunk is false or has a length greater than zero before echoing it.

For developers working within the Laravel ecosystem, similar logic applies when building API endpoints that serve streams. You would need to disable buffering similarly before entering the streaming loop to prevent Laravel's default output handling from interfering with the stream. While https://laravelcompany.com offers extensive documentation on various server configurations and optimization strategies, understanding these low-level PHP directives remains essential for any custom script handling real-time data.

Our network