Using gzip compression on PHP pages

1. Introduction

One of the frequently overlooked functions of servers with PHP of versions 4.04 and above is the ability to compress output. By compressing output, you can speed up page load times and reduce bandwidth.

2. Alternatives

If you are using Apache as a web server, the preferred way to accomplish compression is to use mod_deflate. Another way to transparently compress your pages is to set "zlib.output-compression"

3. Test your server installation

First, check that your server supports gzip compression.

Create a file, phpinfo.php and upload to your webserver to test:


Look for the values for HTTP_ACCEPT_ENCODING -- you should hopefully find the values gzip,deflate meaning compression is supported.

4. Enabling output buffering

Once you've determined that your server supports gzip, you will need to turn it on in your PHP code.

Turn on output buffering with ob_start

ob_start -- Turn on output buffering.

bool ob_start ( [callback output_callback [, int chunk_size [, bool erase]]] )

While output buffering is active no output is sent from the script, it is stored in an internal buffer until ob_end_flush is called to output the buffer to the browser at the end of the request.

Calling ob_start with ob_gzhandler

Now, add the callback function ob_gzhandler which will determine what type of content encoding the browser will accept ("gzip", "deflate" or none at all).

Ensure that the following line appears at the top of the pages that you want compressed:


Flush the output to the browser with ob_end_flush

At the end of the pages that you've set to compress, ensure that you include the following line of code:


5. Test that it works

You can test if your browser supports gzip'ed content, and if your site is using gzip here.

You can also use wget to test if your pages are now gzip'ed:

wget --header="Accept-Encoding: gzip,*" -S

           => `index.html'
Connecting to||:80... connected.
HTTP request sent, awaiting response...
  HTTP/1.1 200 OK
  Date: Fri, 09 Dec 2005 00:29:04 GMT
  Server: Apache/1.3.33 (Unix) mod_auth_passthrough/1.8 mod_log_bytes/1.2 mod_bwlimited/1.4 PHP/4.3.11 FrontPage/ mod_ssl/2.8.22 OpenSSL/0.9.7a
  X-Powered-By: PHP/4.3.11
  Content-Encoding: gzip
  Vary: Accept-Encoding
  Connection: close
  Content-Type: text/html

6. Results

The following results were obtained from the same site:

without gzip: 121.52 KB

with gzip: 26.49 KB

7. Further tweaks

The compression level is set to 6 by default. A higher compression level means more load on the server's CPU. You might want to experiment with the levels to find a value that will give you a good compression for an acceptable amount of load on the server.

To change the compression level, simply insert the following line before ob_start("ob_gzhandler"):

ini_set('zlib.output_compression_level', 4);

An ideal level would be between 1 and 6.

8. Further reading