Home | Php | JavaScript | SQL | HTML | Server Admin | Tools

Gzip Compression
Date and Time
Sending Mail
Header Last Modified
Other sites
Image Editor
Top 10 web hosting reviews

How to enable gzip compression with Php.

Enabling Gzip Compression

In many forums and on many webpages it has been widely proclaimed that to enable gzip compression using php is as easy as adding a single line of code at the beginning of each page. This is not false, however it is not the best way of doing it. Before continuing, here's the code. It takes advantage of Php's buffered output and buffers all output of the script until the Php engine has completed, and then runs all the output through a special function that gzip compresses it before sending it on to the browser.

Here is the code. Just place this at the very top of all your Php pages and it will send gzip-compressed output to the browsers.

Example Code

This method is dependant on the Apache server and in addition, the mod_gzip module must be installed and loaded.

Other Methods to Enable Gzip Compression

The method mentioned above is quick and easy, but the downfalls are that it only works on Apache with mod_gzip. Not only that, but according to the Php manual, that is not the preferred method for gzipping.

(From the Php manual at www.php.net)
note that using zlib.output_compression is preferred over ob_gzhandler().
Another method of gzipping is as follows:

Example Code

// Include this function on your pages
function print_gzipped_page() {

headers_sent() ){
$encoding false;
strpos($HTTP_ACCEPT_ENCODING'x-gzip') !== false ){
$encoding 'x-gzip';
strpos($HTTP_ACCEPT_ENCODING,'gzip') !== false ){
$encoding 'gzip';
$encoding false;

$encoding ){
$contents ob_get_contents();
header('Content-Encoding: '.$encoding);
$size strlen($contents);
$contents gzcompress($contents9);
$contents substr($contents0$size);

// At the beginning of each page call these two functions

// Then do everything you want to do on the page
echo 'Hello World';

// Call this function to output everything as gzipped content.


Link back to this page

Copy and paste this HTML code into your page to link back to this very page:

Or just link to the WebCodingTech site:

And your link will look like this:
      Inspired by stuff found at www.webcodingtech.com.


Copyright © 2005 WebCodingTech.com Our URL is: http://www.webcodingtech.com