Php documentation says, that ob_gzhandler
requires zlib
extension to be installed, so make sure it is true:
if (extension_loaded('zlib')){
echo "zlib installed";
}
If it's installed, you can use ob_gzhandler
and content will be compressed. The problem is you don't see HTTP header Content-Encoding: gzip
in response headers. This header is not set by your web server, but you can set it from php, by means of header()
function:
header('Content-Encoding: gzip');
So, combining these two step you have a solution:
if (extension_loaded('zlib') && !ini_get('zlib.output_compression')){
header('Content-Encoding: gzip');
ob_start('ob_gzhandler');
}
I also check .ini
configuration. If zlib.output_compression
is On
, all output will be compressed, so ob_gzhandler
is redundant.
This code is valid, but it's not what php sould be used for. Compressing output and setting headers is web server responsibility. Please, read relevant answer, about configuring .htaccess file, so Apache will do a compression and set correct response headers for you.