Use your left/right keys to browse tutorials
Caching Dynamic PHP pages easily

Caching Dynamic PHP pages easily

1 Star2 Stars3 Stars4 Stars5 Stars
Posted on February 17, 2009

I’ve been looking for a solution to cache heavy pages and just serve a static html version for a little while now, and I’ve found a solution in output buffering.

Things to think about

It’s not a good idea to go away and cache your entire site, you need to think about which pages receive high traffic, and which pages make a number of database requests. Static HTML pages aren’t going to see a benefit from caching and may in fact be served slower due to PHP invoking the request to the cached version. as an example I’m using caching on dotdashcreate.com homepage as there are a number of database requests that could easily be cached, the cached version of the page is stored here.

If you run a big site or blog I would certainly recommend caching your homepage as this will usually be your visitors first point of contact thus generating more traffic. Its probably not a good idea to cache individual posts that allow comments etc, unless you are willing to write a script to re-cache the page.

You need to allow write access to the cache directory, in the code example this is /cache/. There’s quite a bit going on in the script, the first two lines set the path to the cached directory and the time frame to refresh the cache, we then do a check to see if the cached file is older than the cache time, if it is then it refreshes the cached version (which is the block of code at the bottom), if not it just serves the cached version.

The Code:


$cachefile = 'cache.html';
$cachetime = 4 * 60;
// Serve from the cache if it is younger than $cachetime
if (file_exists($cachefile) && time() - $cachetime < filemtime($cachefile)) {
    include($cachefile);
    echo "<!-- Cached copy, generated ".date('H:i', filemtime($cachefile))." -->\n";
    exit;
}
ob_start(); // Start the output buffer

/* Heres where you put your page content */

// Cache the contents to a file
$cached = fopen($cacheFile, 'w');
fwrite($cached, ob_get_contents());
fclose($cached);
ob_end_flush(); // Send the output to the browser

demo



More tutorials from Papermashup
Comments
63 discussions around Caching Dynamic PHP pages easily
Newer Comments
  1. jebaird says:

    First off I have gota say that this caching idea kicks ass.
    I have created a class based on the original code and user comments code. Also i fixed a couple of bugs:

    here is the link:
    http://www.jebaird.com/blog.php?year=2009&month=03&cat=3&id=32

  2. Used it, in my “freshly” created cms. Works like a charm!

  3. AzeriFire says:

    Thank you admin :)
    There are some new correction too:
    Replace this one:

    if (isset($_SERVER['REQUEST_URI'])) // Is there any URI to cache
    

    with this one:

    if (isset($_SERVER['REQUEST_URI']) && $_SERVER['REQUEST_URI']!="/") 

    to escape problems when site URL ends with slash (http://site.com/)

    Latest version is here:
    http://paste.org/5666

    P.S. Sorry for spam

  4. AzeriFire says:

    Hi. Thank you for this little, but powerful code. I use SEF URL on my sites. There are problem with “/” (slash). If site URI ll be for sample – /nokia/n97/comments/page/1.html this cache script will look for cache folder, then nokia folder, then inside of nokia folder for n97 subfolder and etc… There are will be PHP errors on site (Not found page and etc.). I improved it little more.And use global variable to define is the caching this page indeed. For sample, I don’t need caching login page and etc. I use $useCache variable ($useCache=0 to disable, =1 to enable caching currently viewing page.)
    And finally improved script:
    http://paste.org/5665
    OR
    http://www.pastethat.com/use_cache_with_p

    Thanks again!
    P.S. Sorry for my poor English.

    • admin says:

      AzeriFire,

      Thanks for the comments and code update! Glad to hear you found it useful and adapted the code in your own way.

      Ashley

  5. Andrew Gill says:

    Great article. My homepage (index.php) is also calling the database many times. So i’ve used your approach slightly differently by creating an index.html page in the root so there is no need for the include.

  6. Traducciones says:

    nice post! i will use it

  7. Pingback: Wordpress Blog Services - 20 Useful PHP Components &amp; Tutorials for Everyday Project

  8. Pingback: 20 Useful PHP Components & Tutorials for Everyday Project | Noupe

  9. Pingback: Daily Links | AndySowards.com :: Professional Web Design, Development, Programming, Hacks, Downloads, Math and being a Web 2.0 Hipster?

  10. Patternhead says:

    If you’re using using WordPress then the wp-supercache plugin works pretty well!

  11. Ashley says:

    That’s a great point, I should have mentioned that in my post! I’m currently using the wp-supercache plugin, well worth installing if you anticipate spikes in blog traffic.

Newer Comments




Never miss an update from Papermashup

Get notified about the latest tutorials and downloads.

Subscribe by Email

Get alerts directly into your inbox after each post and stay updated.
Subscribe
OR

Subscribe by RSS

Add our RSS to your feedreader to get regular updates from us.
Subscribe

Get in contact

Please use the form below to get in contact. If your question is related to a free script download, please use the comments on the article page as community members are more likely to respond quicker than I can personally.

About Me

I'm Ashley Ford, Co-founder and Technical Director at Harkable.com London, UK. Previously I worked at InMobi, Spotify and MySpace. My interests include photography and making short videos I'm also an avid F1 fan. I'm always working on side projects. Here are a few: Easy Poll, We Deliver.



What do you specialise in?

I spend a lot of time coding in PHP and MySQL, as well as front end XHTML and CSS. I also specialise in javascript and the jQuery framework as well as being an avid designer. You can find me on dribbble

Interested in advertising?

If you'd like to advertise on Papermashup.com please get in touch via the contact link below for advertising opportunities.

How do I contact you

You can contact me here. and I'm available for consultation, freelance, programming book reviews.

Get on the mailing list

Join over 3000 people who have subscribed to the Papermashup inbox message, and be the first to find out about tutorial, competitions and giveaways.