Outputting From User Output Handler is Deprecated in PHP 8.5

Outputting From User Output Handler is Deprecated in PHP 8.5

PHP provides the ob_start function, which accepts an optional output buffer handler function. When provided, the handler function receives the buffered output just before it is sent to the client. The handler function must not produce output itself, but it may inspect or modify the output and must return the final string to be emitted.

In some legacy systems, an output buffer handler function may emit output directly (for example, using echo). That output is silently ignored, and developers may not realize that it has no effect. Since PHP 8.5, emitting output from a handler function is deprecated.

<?php

ob_start(
    static function(string $buffer): string {
        echo 'Test';
        return $buffer.'<footer>'.date('Y').' My Site</footer>';
    }
);
?>
<main>Page content</main>
<?php ob_end_flush(); ?>

Example will output:

Deprecated: ob_end_flush(): Producing output from user output handler ... is deprecated in ...

To fix the deprecation warning, you should avoid producing output inside the handler function. Any output inside a handler is already silenced and not sent to the client. Here's the corrected example:

<?php

ob_start(
    static function(string $buffer): string {
        return $buffer.'<footer>'.date('Y').' My Site</footer>';
    }
);
?>
<main>Page content</main>
<?php ob_end_flush(); ?>

Leave a Comment

Cancel reply

Your email address will not be published.