Cache certain areas of your page using PHP

Sometimes it’s necessary to cache only certain elements or areas of your dynamic page to speed up the load times. I recently needed to cache two DIV’s that were being dynamically generated on one of my websites. They were each taking about 10 seconds to load which as you know, can be detrimental to your SEO efforts. Here’s the steps I followed in order to reduce my page load times from 20 seconds to under 1.5 seconds.

Step 1: Separate the areas

First of all, you would need to make the areas you would want to cache separate from the page. You can do this by creating new files for these areas and using the “include (‘page_name.php’);” function. This allows us to better control that specific file for caching purposes.


<div id="pane_popular">
      // this is one of the divs we want to cache

Step 2: Create the cache directory
Create a directory called “cache” on your web server. We will reference this in step 3.

Step 3: Insert the PHP cache code

Insert the following script at the top of the included file (in this case it’s the ‘div_top_articles.php’ file).


    $cachedir = 'cache/'; // Cache directory
    $cachetime = 600; // Seconds to cache files for
    $cacheext = 'cache'; // Extension to give cached files (usually cache, htm, txt)
    // Script
    $page = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
    $cachefile = $cachedir.md5($page).'.'.$cacheext; // Cache file to either load or create
    $cachefile_created = ((@file_exists($cachefile))) ? @filemtime($cachefile) : 0;
    // Show file from cache if still valid
    if (time() - $cachetime < $cachefile_created) {
    else {
    // If we're still here, we need to generate a cache file
        // ----------------------------------------------------
        // ----------------------------------------------------
        echo "<small><small>Cached on: ".date("Y-m-d H:i:s")."</small></small>";
        // ----------------------------------------------------
        // ----------------------------------------------------
        // Now the script has run, generate a new cache file
        $fp = @fopen($cachefile, 'w'); 
        // save the contents of output buffer to the file
        @fwrite($fp, ob_get_contents());

Code thanks to AddedBytes, modified slightly.

That’s all there is to it.

About the Author:

Nick is the owner of Code Cabin, founder of PingPong and co-founder of AirWeddings. He has an extensive history in programming and digital marketing and has worked on some of the largest online websites in South Africa. Nick shares his knowledge and insight on his personal blog,

NickDuncan – who has written posts on Nick Duncan.

Email • Google + • Twitter

Tags: , , , ,

No comments yet.

Leave a Reply