MacdougalMedia by Scott Macdougal Weaver

30Jun/099

Compress PHP Output And Save On Bandwidth!

We all love web pages that load super fast and as Google pushes us to "make the web faster," we must heed the call.

In my search for ways to increase efficiency while decreasing page load times and bandwidth output, I happened upon the wonderful world of Zlib compression. This compression type uses gzip to compress the output of your files and feed them to the browser.

How cool is that?

While it might sound like it would be an impossible task, it's really as simple as doing two things-

Step 1. Make sure your PHP server has the zlib extension

All you have to do is create a file called something like phpinfo.php on your server and put the following code inside:

<?php

phpinfo();

?>

Once it loads, just find 'zlib' and check to see whether it's there and whether it's enabled. If not, you need to either enable it yourself or ask your server admin to do it.

Step 2. Pop in the code!

Put the following code at the very top of any pages you want compressed, or (preferably) in your header file for the entire site-

<?php

ini_set('zlib.output_compression', 'On');
ini_set('zlib.output_compression_level', '1');
?>

OR if that doesn't work for you, you can try this-

<?php

ob_start('ob_gzhandler');

?>

...that's it!

Now try reloading your page.

If everything went right, you should notice an improvement in load time and where you'll notice it most is in your bandwidth usage at the end of the month.

I tested the before and after on Sitdiary.net and the file got compressed by over 3X every time! In other words, I'm going to cut my bandwidth usage down by 2/3 on all PHP files.

*** UPDATE ***

On my WordPress blogs, I've been testing this out on the index.php and it seems I'm getting upwards of 75% compression rates!

Tagged as: , , 9 Comments