Why to use compression? It can greatly reduce data transfers at the cost of increasing cpu load on your server. I made tests, and from 100kB HTML document it made 10kB one, so when you have your machine on some slow line, it is like a blessing.

So, let's begin.

1) Easy Way

<?
ob_start("ob_gzhandler");

echo "This is a compressed page! :)";
?>

Yes, this is the easiest way to user gzip compression to reduce the size od your pages. ob_gzhandler will check, it browser supports gzip comression, send correct headers, compress data and send it to the client.
BUT: In php 4.0.4pl1 and older, there is huge memory leak, that makes this unusable. For some time, I used it with "MaxRequestsPerChild" directive in httpd.conf of my Apache Web Server set to value about 500, so when apache grew larger, the child process was killed and memory was restored.

2) Hard Way

After few days of studying documentation I found this way. It does the same as the first one, but if doesn't use ob_gzhandler function, so you can use it safely anywhere.

<?
if(strstr($HTTP_SERVER_VARS['HTTP_ACCEPT_ENCODING'], 'gzip')):
   ob_start();
   ob_implicit_flush(0);
endif;

echo "This is a compressed page!";

if(strstr($HTTP_SERVER_VARS['HTTP_ACCEPT_ENCODING'], 'gzip')):
   $obsize = ob_get_length();
   $contents = ob_get_contents();
   ob_end_clean();
   Header("Content-encoding: gzip");
   Header("Content-length: ".$obsize);
   echo "\x1f\x8b\x08\x00\x00\x00\x00\x00"; //gzip file header
   $size = strlen($contents);
   $crc = crc32($contents);
   $contents = gzcompress($contents, 9); //"9" is the level of comression (0-9)
   $contents = substr($contents, 0, strlen($contents) - 4);
   echo $contents;
   echo pack("V",$crc);
   echo pack("V",$size);
endif;
?>

Log in or register to write something here or to contact authors.