May 16, 2006

ZLib output compression in PHP

You will find other articles relevant to this document in these sections:
Cameron Manderson @ 5:46 pm

We can make use of ZLib output compression in PHP to compress the HTML output for transport across HTTP (if the browser supports it). This requires a little more server processing time, but can lead to significant speed increase in the transportation of your HTML.
In PHP we need to collect our output in a buffer, then compress it, then send the relevant HTTP headers. PHP can manage most of this for us with an inbuilt gzhandler which determines support for GZIP transmission.
At the top of our script (Or in MVC this could be included in our ActionDispatcher) where we start to produce output we set ZLib event handling on:

// Set the ZLib for compression
ini_set('zlib.output_compression_level', 4);  // 1-9 4=Not too CPU intensive

We then start our output buffer which calls back the function “ob_gzhandler” when we flush it.

ob_start("ob_gzhandler");

At the end of our script once we have generated all our output, we need to flush/clean out our buffer, with the call:

ob_end_flush();

You can use FireFoxes Live HTTP Headers plugin which allows you to see that your PHP page is correctly generating your compressed output. You should see a request by your browser, such as:

GET /index.php?do=task HTTP/1.1
Host: localhost
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.0.3) Gecko/20060426 Firefox/1.5.0.3
Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Connection: keep-alive
Cookie: PHPSESSID=ABC123ABC123ABC123ABC123ABC123ABC123
Cache-Control: max-age=0

Followed by a response such as below:

HTTP/1.x 200 OK
Date: Tue, 16 May 2006 06:38:28 GMT
Server: Apache/2.2.0 (Win32) DAV/2 mod_ssl/2.2.0 OpenSSL/0.9.8a mod_autoindex_color PHP/4.4.1-pl1
X-Powered-By: PHP/4.4.1-pl1
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache
Content-Encoding: gzip
Vary: Accept-Encoding
Content-Length: 2074
Keep-Alive: timeout=5, max=95
Connection: Keep-Alive
Content-Type: text/html

If you are trying to make large blocks of HTML transmit faster, at the very very very slight performance degredation server side generating the file this may be an appropriate way of speeding up your clients requests. You could even incorporate this into your caching algorithm, and extend the callback function to cache the compressed content.

Share and Enjoy:These icons link to social bookmarking sites where readers can share and discover new web pages.
  • del.icio.us
  • digg
  • Furl
  • Reddit
  • YahooMyWeb

No Comments »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a comment