ob content cannot be clean from ob callback when exits/throws
Description
Original report https://bugs.php.net/bug.php?id=78565
The following code:
<?php
// capture any unexpected output and exit execution
ob_start(function($buffer) {
echo 'unexpected output: ' . $buffer . "\n";
exit;
}, 1);
// do some work on shutdown
register_shutdown_function(function() {
ob_flush();
ob_end_clean();
echo 'shutting down';
});
echo 'x';
Resulted in this output:
xunexpected output: x
unexpected output:
But I expected this output instead:
unexpected output: x
shutting down
PHP Version
8.0+
Operating System
any
ob_flush causes another call to callback with empty buffer: https://3v4l.org/aYQ92 Technically this is calling exit inside shutdown handler.
If you call exit() within one registered shutdown function, processing will stop completely and no other registered shutdown functions will be called. register_shutdown_function
ob_flushcauses another call to callback with empty buffer: https://3v4l.org/aYQ92 Technically this is calling exit inside shutdown handler.If you call exit() within one registered shutdown function, processing will stop completely and no other registered shutdown functions will be called. register_shutdown_function
you are correct, thanks!
https://3v4l.org/riNB9 - how can I clean the ob buffer inside ob_start callback?
my desired output is:
-xunexpected output: x
+unexpected output: x
shutting down
ob_clean is not allowed inside ob callback - https://3v4l.org/qm2gf - and there cannot be a return '' statement as exit exists
This is a bit hacky, but works. Callback in ob_start have to return value to prevent output, but we can exploit garbage collector to stop execution after handling callback return. As far I know, there is no other way. Also, probably better would be to use Error and set_exception_handler. https://3v4l.org/fh9ds
<?php
function debug($msg){
fwrite(STDOUT, sprintf("[Debug] %s\n", $msg));
}
// capture any unexpected output and exit execution
ob_start(function($buffer, $phase){
// prevent exit on ob_end_*()
if(($phase & PHP_OUTPUT_HANDLER_FINAL) === 0){
$f = new class ($buffer) {
public function __construct(private $buffer) {}
public function __destruct() {
debug('exit call');
exit();
// or
// throw new UnexpectedOutputException($this->buffer);
}
};
}
debug(sprintf("callback called, buffer: %s, phase: %d", var_export($buffer, true), $phase));
// prevent buffer output
return null;
}, 1);
// do some work on shutdown
register_shutdown_function(function() {
debug('ob_end_clean');
ob_end_clean();
debug('shutting down');
});
debug('echo x1');
echo 'x1';
debug('echo x2');
echo 'x2';
Output:
[Debug] echo x1
[Debug] callback called, buffer: 'x1', phase: 1
[Debug] exit call
[Debug] ob_end_clean
[Debug] callback called, buffer: '', phase: 10
[Debug] shutting down
@KapitanOczywisty very nice, thanks!!!