Jimmy's Blog Jimmy Ruska's Blog
Cache Slow Pages for Performance Posted on Friday, April 4 2008
Learn to Play Songs by Ear: Ear Training

If you have a certain page that takes a significant amount of time to output data you should cache the output. You don't need to cache the whole page, you can cache any and as many parts as you'd like.

Example: Slow.php


function showMessages(){


echo $output;


Lets say showMessages() is a function that is slow loading. Every time a user goes to a new page it queries to check if you have any new messages / emails / whatever you want to imagine it as. Instead, lets make it update in more reasonable intervals like every minute.

What steps need to be done to cache?

  1. Save the output to a cached file
  2. At the start of the code check if that cached file exists
  3. Check how long ago the cached file was modified
  4. If modified not long ago load the file into output instead of calling the action

Example: Fast.php


function showMessages(){


// Step 2: Check if file exists

if (file_exists('cachedfile.txt')){

// Step 3: Check how long ago it was cached

$t=60; // Required time in seconds since last change before run again
if ((time()-filemtime('cachedfile.txt')<$t){

// Step 4: Get contents of cache into $output
echo $output=file_get_contents('cachedfile.txt');


if ($needsCaching){
echo $output;

// Step 1: Cache output
$open = fopen('cachedfile.txt', "wb");
fwrite($open, $output);


What about Dynamic Pages?

You can set the cached file name to the post id or query name. If you have multiple parameters in a search you want to cache you could concatenate the queries and use them as the file name. If you have especially long queries or queries with sensitive data you could md5 the concatenated parameters and save it as the cache file name.

What about weekly / daily caching?

If you have a file that's updated once a day or slower, you probably don't want the script making a time comparison every time its loaded. It may be better to setup a cron job to cache the output or multiple outputs at preset intervals of time. Cron jobs aren't always better though, it depends on what you're doing.

Efficient Database Caching

Try memcached. It stores results in memory rather than files. I wouldn't run it unless you have loads of ram or an extra server though.

Tags: cache pages php, cache mysql output, caching slow files, howto, memcached, linux, windows, apache

stumble digg delicious

Blog by Jimmy Ruska
Add me: Youtube, Twitter, Facebook, MySpace


More OMFG-Good Links

See all Posts in the Funny Pictures category.
Download mp3s faster than limewire using google.
I've made 100+ free video tutorials.
See the best of the internet today on one page.