Caching and Compressing your site

If you have a large, dynamic website that uses many SQL calls you may want to cache your pages. And while you are at it, you can compress the cache too!

To use this tutorial you’ll need to have the zlib extension.

htaccess command
php_value auto_prepend_file /home/path/cache_begin.php
php_value auto_append_file /home/path/cache_end.php

By inserting these commands into your .htaccess file, you are telling it to include cache_begin.php before the script, and cache_end.php after the script. These files will contain the cache code, so you can cache all the php pages on your site without having to modify them all.

cache_begin.php

What cache_begin does, is it first makes up a cache file name. This name is just the MD5 of the REQUEST_URI. The MD5 keeps a unique name, but also removes any slashes and such from the filename. Using the REQUEST_URI, if you have site.php?page=2, it will generate a different cache than site.php?page=1

It then takes that cache name, and sees if the file exists. If it does, it then checks if the last time it was modified within the expiration. If it wasn’t, or if the file didn’t exist, it runs the scripts and caches the output. If it was, it displays the cache file and exits.

@ob_start(‘ob_gzhandler’); is what buffers the output, and compresses it with Zlib. If you want to cache your pages, but don’t have zlib, you can just use @ob_start(); – however I’d recommend you ask your host to install it if you dont ;-)

Things to note – $time_c23 is in seconds (86400 = 24 hours), the _c23 in the variables mean nothing – they just prevent you from overwriting the values within your script.

cache_end.php

This script is only executed when the cache needs to be generated. It takes the output buffer and saves it to the cache file, and then outputs it to the browser.