ParoX
ParoX

Reputation: 5933

How to properly flush buffer without error suppression

I found this snippet many years ago, it's always done me well but I found out recently that error_get_last() and any custom error handlers will ignore the @ and still trigger.

The recommended approach is to check if error_reporting() == 0 as per https://www.php.net/manual/en/language.operators.errorcontrol.php#104545

Instead of making a hacky workaround for a hacky workaround, I'd rather not use error suppression at all, but it's not clear to me how properly set up conditionals to have this snipper run properly. Google searches indicate to use ob_get_level(), ob_get_length() and ob_get_contents() in various but conflicting ways.

What is the best way to remove the error suppression and add if statements checks to the following:

// Fill-up 4 kB buffer (should be enough in most cases).
echo str_pad('', 4 * 1024);
echo '<!-- -->';

// Flush all buffers.
do {
    $flushed = @ob_end_flush();
} while ($flushed);
@ob_flush();
flush();

Upvotes: 0

Views: 441

Answers (1)

Olivier
Olivier

Reputation: 18067

As indicated in this note, flushing all output buffers can be done this way:

while (ob_get_level() > 0) {
    ob_end_flush();
}

flush();

Upvotes: 2

Related Questions