Published in


Fixing A Strange PHP Gzip Issue

Photo by Tomas Sobek on Unsplash
  1. An old software they had that analyzed the links of pages of the site was crashing on his rewrite not even getting so far as parsing the markup, odd since it is more modern and uses XMLDocument and his output markup was valid!
  2. Errors were showing up in his error log but not in the output despite “all” error reporting being enabled.
  3. A number of pages were delivering blank white nothing, zero content in the response.

PHP.INI Zlib Is Convenient, Not Reliable

One of the first things he did in the recode was to pull out ob_start() with the old-school manual compression method. From before gz_handler was even an option. In its place he just enabled compression in the PHP.INI with:

zlib.output_compression = "1"

Output Buffering

A number of the pages that were crashing were trying to set cookies or headers after output started. If you know anything about PHP — or web dev in general — you know you can’t do that… so why did it work in the old program?

The Solution?

Go back to doing it manually, just with a more modern approach. As it’s a single entry program it’s easy to hook the compression right at the start. Turn off the php.ini compression, go back to ob_start but using gzhandler instead, and use register_shutdown_function to handle setting the header() and flush.

foreach (['gzip', 'x-gzip', 'x-compress'] as $type) {
if (strpos($_SERVER['HTTP_ACCEPT_ENCODING'], $type) !== false) {
define('CONTENT_ENCODING', $type);
ob_start(defined('CONTENT_ENCODING') ? 'ob_gzhandler' : null);
register_shutdown_function(function() {
if (defined('CONTENT_ENCODING')) header(
'Content-Encoding: ' . CONTENT_ENCODING


This was a simple fix, and has let my friend go forward in debugging his rewrite. I’ve always used code similar to this from almost the day I started using PHP decades past, just because being able to use header and cookies wherever is needed greatly simplifies using the language.



Everything connected with Tech & Code. Follow to join our 1M+ monthly readers

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Jason Knight

Accessibility and Efficiency Consultant, Web Developer, Musician, and just general pain in the arse