Save Bandwidth – Enable GZip Compression In PHP

GZip is a formidable way to save up on bandwidth, without hindering your users. It allows any script to pass its content by the compression tool first, before being sent out. The receiver will then receive the compressed file, and unpack it to show its content.

Browsers that don't support GZip will automatically fall back to the normal way of sending out content: unzipped.

It's a win-win situation. You save bandwidth, and don't bother your users. So, let's enable it.

The easiest is way is by using a .htaccess file. Add the following line to it.

php_value output_handler ob_gzhandler

That simple line will reduce the bandwidth used by plain text files (html, css, javascript, rss, ...) by as much as 80%. It doesn't do much for images (JPG/PNG is a formidable compression on its own, and can't be compressed much further), but it's a saver for anything that isn't image/video.

Since not every host allows .htaccess to overwrite certain system settings, you can also define this in your PHP pages itself, as described on the following page: Other Methods to Enable GZip Compression.

You can quickly test the result of your compression, at the following website: compression / deflate / gzip test tool.

There 's a (relatively) small downside to this: it requires a bit of CPU power from your webserver to compress the page, and a bit of CPU power from your visitor to decompress the page. This probably won't be an issue, unless you have a very busy server.

Hi! This is a blog where I write down solutions to some of the problems I've faced when working as a sysadmin/dev. I hope you find the information shown here useful to you. Please use the comments on this blog to give feedback about the content!. I'm @mattiasgeniar on Twitter.

Tagged with: , , ,
Posted in php
6 comments on “Save Bandwidth – Enable GZip Compression In PHP
  1. lulz says:

    php, you say? i luled.

  2. Matti says:

    It uses the Output Buffering built into PHP, to compress the pages before output. How’s that not PHP mister “I luled”?

  3. stelian says:

    I know this is not the right place to write this, but it would be nice if I could see the date on the first page for every post.

  4. Matti says:

    You’re quite right, it’s been added to the frontpage. :-)

1 Pings/Trackbacks for "Save Bandwidth – Enable GZip Compression In PHP"
  1. [...] possible to save money: we hosted our static site resources (css + images) on a different host, we gzipped all our server-content before sending it to the user (which actually saved us about 95% in bandwidth, due to the textual nature of all our content being [...]

Leave a Reply

Your email address will not be published. Required fields are marked *



You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>