I'm using PHP 7.1 and I'm using the following pseudo-code to generate my website:

<?php ob_start("ob_gzhandler", 0, PHP_OUTPUT_HANDLER_CLEANABLE); try{ echo "<h1>My awesome webpage!</h1>"; ... more code that can throw exceptions... echo "<h2>Welcome to my awesome webpage!</h2>"; }catch(\Throwable $e){ ob_clean(); echo "My awesome webpage crashed :(("; }

When no exceptions is thrown, all works as expected: the website is outputted and compressed. You can see the result here

But, when an exception is thrown, something unexpected happens (link to the result): as desired, only the text outputted after ob_clean() is sent to the browser, but it cannot decode it correctly.

The problem seems related to the fact that the browser doesn't recognize the output of the page as compressed.

Digging into the issue, it seems that, when ob_clean is called, the header content-encoding is not sent to the browser. To confirm this hypothesis, I tried to manually set that header, and everything works as expected (link).

<?php ob_start("ob_gzhandler", 0, PHP_OUTPUT_HANDLER_CLEANABLE); try{ echo "<h1>My awesome webpage!</h1>"; throw new \Exception("Whops"); echo "<h2>Welcome to my awesome webpage!</h2>"; }catch(\Throwable $e){ ob_clean(); header('content-encoding:gzip'); //Why PHP?... WHYYY?!?!? echo "My awesome webpage crashed :(("; }

My question is the following: since ob_start("ob_gzhandler") doesn't always use gzip compression (e.g. when the browser doesn't support it), my work around of manually setting the header is not viable. How can I achieve the same result without using some horrible hack?