Simple PHP caching

There are many tools around that will help cache your website to increase speed and performance, such as eAccelerator and APC. However these usually require installation on your web server, thus rendering them useless for people who use shared hosting and don’t have access to the server.

Using some simple PHP code we can quite effectively cache a webpage, useful for sites that are database driven and have a large amount of queries or high volumes of traffic.

First we need to setup the folder where the cached files are stored, making sure it has read/write permissions (CHMOD to 0777 – see your FTP client documentation on how to do this).

Next create a file called cache.php which contains the following code:

 

Now in your page you would include cache.php on the first line before you do anything else. This is because if the page is cached we don’t want it to do anything else other than output the cache to the page. If you are still including other files or connecting to databases before checking for the cache you are putting additional load on the server, making this exercise pointless.

Finally create a file called cache_footer.php which contains the following code:

You would include this file on the last line of your page, which saves the page in the cache if required.

Putting it altogether a typical page would look like this:

 

Leave a Reply

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