How to use Gzip to load your site faster in 5 minutes

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.

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:

output_buffering = Off
output_handler =
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.

Step 2: If you want use gzip to compress other files, javascript, css, etc:

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.

1. Rename core.js to something like core.js.php
2. Open core.js.php in your favourite text editor and add this to the beggining of the file (before anything else) then save:

<?php header("Content-type: text/js"); ?>

3. Reference core.js.php in your html just as you would normally, the browser will see it as a JS file, not PHP:

<script language="javascript" src="core.js.php" type="text/javascript"></script>

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.

Share this Post:
Digg Google Bookmarks reddit Mixx StumbleUpon Technorati Yahoo! Buzz DesignFloat Delicious BlinkList Furl

Comments are closed.