phphhvm

failed to flush buffer. No buffer to flush with ob_end_flush() method


My site is streaming mp3 file, intermittenly I saw Notice error in log file:

Notice: failed to flush buffer. No buffer to flush in

Below is the code:

$filename = 'audio.mp3';
header("Content-Type: audio/mpeg");
header("Content-Length: ".filesize($filename));
header('Content-Disposition: inline; filename="' . $filename);
header("X-Pad: avoid browser bug");
header("Cache-Control: no-cache");
ob_clean();
flush();
set_time_limit(0);
$size = filesize($filename); 
$chunksize = 1 * (1024 * 1024);
if ($size > $chunksize) {
    $handle = fopen($filename, 'rb');
    $buffer = '';
    while (!feof($handle)) {
        $buffer = fread($handle, $chunksize);
        ob_start();
        echo $buffer;
        ob_end_flush();
        flush();
    }
    fclose($handle);
} else {
    readfile($filename);
}

The error always refers to ob_end_flush(); line.


Solution

  • So, looking at the PHP source for ob_flush(), which is where the "failed to flush buffer. No buffer to flush" error is being generated, it appears that error is generated if there's no active output buffer.

    Based on the PHP source, ob_end_flush() should never result in that error - it can't, it's not in the code. Are you sure you don't have an ob_flush() somewhere in your code that you're not including in what you're sharing with us in your question?

    Anyway, you're not checking the return value of ob_start() - it can fail, and if it fails to create a new output buffer, then a subsequent ob_flush() or ob_end_flush() will fail because those commands require an active output buffer in order to function, and if there isn't one, they will emit errors.

    You can see in the PHP source for ob_end_flush() that the error it emits when there is no active output buffer is "failed to delete and flush buffer. No buffer to delete or flush".