Simple PHP Caching System

In this tutorial, I will show you how to set up a very simple page cache using PHP. If you have a PHP page that takes a very long time to load and the content changes less then once every few minutes, then this tutorial is for you. Since, more times than not, it is your home page that will need cached, probably because it often takes the longest to load due to all the graphics and special features in a modern website, I will show you how to cache your home page. You could apply the same principle to any page of your site or all pages if you wanted to.

NOTE: If you copy and paste anything from this or any other WordPress blog, you’ll have to convert fancy single and double quotes to plain ones in notepad. If you script doesn’t work this is often the reason why. Also be aware of where lines are supposed to break particularly on commented out text lines.

Step 1 – Rename your index.php file

Your home page is probably index.php. If not, make the change to the appropriate page. Change the name of index.php to index-non-cached.php.

Step 2 – Make a new index.php file

Open your text editor and copy and paste the following code into it:


include ‘c.php’;
$result = mysql_query(“SELECT * FROM hmpg_cache WHERE id=’1′”)
or die(mysql_error());
echo html_entity_decode($r[‘HTML’], ENT_QUOTES);
//echo str_replace(‘~’,'”‘,$allHTML);
}//end while.
//echo “script done…”;

Now that you have your new index.php file, you should be able to see that you have a couple steps to do to make it work. Notice where it includes c.php at the top. c.php needs to be created. It is your database connection. Which brings us to another necessary step, creating a database. Read on and I’ll show how.

Step 3 – Create your Database

A simple cache requires only a simple database. In fact, if you already have a database, you could just add a table to it. Name your table hmpg_cache and it only needs 3 columns, id, date and html. Here’s a screenshot. I assume if you are good enough at programming to attempt building a cache in php, then you should be able to figure out how to make the database table from this image:


Okay now that you have your database table, write a simple c.php file to connect your script to your database like this:

//connect to database:
$url = “localhost”;
$user = “db_user”;
$pass  = “db_pass”;
$dbname = “db_name”;
$con = mysql_connect($url,$user,$pass);
mysql_select_db($dbname) or die(“ERROR, Could not select the $dbname database!”);

There you have it. Be sure to insert the proper values in the above c.php file. Now I like to make a directory named cron and put my database connection file, c.php, there. Also in the cron directory will go the cache engine which will eventually be ran on a cron job, so the cron directory name is appropriate.

Step 4 – Create a Caching Engine

This is the heart of the simple PHP cache system, the cache engine. I named my cache file home-page-cache.php, but as with any other names I use, you are free to use your own names as long as you modify everything to make it work. Here is the contents of my home-page-cache.php file:


//record time of cron run:
$time =  date(“F”);
$time .= (” “);
$time .=  date(“d”);
$time .= (“, “);
$time .=  date(“Y”);
$time .= (” at “);
$time .=  date(“h:i:A”);

//initial line for email:
$emltxt = “Cron job ran on: “.$time.”\n\n”;
echo “Cron job ran on: $time<br />”;//exit;
$theurl = “Path-to-home/index-non-cached.php”;//change path
$emltxt.=”URL being read into database: $theurl\n\n”;
echo “URL being read into database: $theurl<br /><br />”;
//get HTML of home pg and parse:
    if (($allHTML=file_get_contents($theurl)) !== FALSE) {
    $allHTML = htmlentities($allHTML, ENT_QUOTES);
    //echo $allHTML;
    //die(“ian killed script here…”);
    $emltxt.=”successfully collected Home Pg HTML into a PHP variable.\n\n”;
    echo “Successfully collected Home Pg HTML into a PHP variable.<br /><br />”;
    $emltxt.=”ERROR! Failed to insert Home Pg HTML into PHP variable.. tried to get content from $theurl.\n\n”;
    echo “ERROR! Failed to insert Home Pg HTML into PHP variable.. tried to get content from $theurl.<br /><br />”;
//insert or update home pg HTML in the hmpg_cache table of database
//see if row 1 exists and if not create it:
include ‘c.php’;
$test = mysql_query(“SELECT * FROM hmpg_cache WHERE id=’1′”)
or die(mysql_error());
$rw = mysql_num_rows($test);
    if($rw < 1){//if no rows, do insert
    mysql_query(“INSERT INTO hmpg_cache (HTML) VALUES(‘$allHTML’)”)
    or die(mysql_error());
    $emltxt .= “<p>DB successfully Inserted!</p>”;
    }else{//else if row 1 exists, do update
    //only do if allHTML has content:
        if($allHTML != “”){
        mysql_query(“UPDATE hmpg_cache SET HTML=’$allHTML’ WHERE id=’1′”)
        or die(mysql_error());
        $arows = mysql_affected_rows();
            if($arows > 0){
            $emltxt .= “<p>DB successfully updated!</p>”;
            $emltxt .= “DB Errror! no rows were affected.<br />”;
        $emltxt .= “Error! No html content found.<br />”;
        }//end else no html content found.
    }//end else update db.
//echo str_replace(“\n”,”<br />”,$emltxt);//alternative method for showing text in browser
//write to log file:
$myFile = “/var/www/html/cron/cronLog.txt”;//edit path
$fh = fopen($myFile, ‘a’) or die(“can’t open log file to write”);
//mail(‘’, ‘Home Pg Caching’, $emltxt);//for running with cron

Now you have a good start for your cache engine. First use it in your browser until you get it working exactly how you wish, then comment out the echo statements and use it to set up a cron job. Hopefully you know how to create a cron job, but if not, see my cron tutorial at for cpanel users and at for how to do it without cpanel. When you turn it into a cron job, it is set up to email you, so be sure to change the email address towards the bottom of the script to your own. Un-comment that line to make it send emails as well.

Wrap It Up

Okay now all you need to do to engage your new PHP Cache Engine is to navigate to where you put your cron engine, such as and that will cause the page to be cached for the first time. Then check your database to be sure it filled line 1 with data. If so, go to your previously slow loading index page and watch it load in a second or two! Good Job!

Leave a Reply

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