How to use Gzip to load your site faster
Lately I’ve been reading various random articles about some browsers ability to deflate zipped webpages, so that there is less bandwidth and faster loading times for websites. Although this ability has been around for a while, it’s only been lately that I have a need to use it.
For those rare browsers that do not support compression, they just receive a non-compressed page. So effectively, you’d be nuts not to use compression on your site. There’s nothing to lose (apart from a slight server load increase, but I’m told Slashdot uses compression even with it’s large amount of site hits).
Here is a real world example of a page compressed with Gzip:
This tutorial will only examine one particular way of implementing Gzip compression with PHP, but there is another way to accomplish it with Apache if you have administration access to your server.
How to implement Gzip compression in 5 minutes
Step 1: Enable zlib compression in PHP. You can do this many ways, just choose one:
- Add a line to your .htaccess file:
php_flag zlib.output_compression On
- Add or change a line in your php.ini file:
zlib.output_compression = On
- Add a line to the top of your PHP scripts before any output:
Now that you’ve done that (and particularly with the first 2 options), any file that is passed through PHP will be Gzipped if the browser supports it.
If your file does not pass through PHP before it is outputted, you can change the extension of the file to .php and it will be compressed. For this example I’ll use core.js.
- Rename core.js to something like core.js.php
- Open core.js.php in your favorite text editor and add this to the beginning of the file (before anything else) then save:
<?php header("Content-type: text/js"); ?>
- Reference core.js.php in your html just as you would normally, the browser will see it as a JS file, not PHP:
So to explain, we rename the file to make it a php file, so it is passed through the PHP compiler. Then we add a mime header line to the file, so that the browser knows what type of file it’s meant to be. Then we reference the file (if it’s a CSS or JS file for example) just as we normally would.
Remember to change the mime type to text/css for CSS files.
A quick note with this method. Only compress files that are specifically meant for a web browser (html, js, css, and xml). If you try this with a PDF file, for example, it works in browsers, but not when saved and displayed in Adobe PDF Reader.
If you’re finding that this method causes errors in your scripts, chances are that you haven’t got the zlib module installed with PHP.