For dynamic websites, database queries take up a significant amount of the CPU resources of your servers. For medium to high traffic websites in shared or virtual hosting services, this could mean significant loss of traffic due to too much database queries or over use of shared CPU time. As such, it is quite useful to have some sort of cache system for your dynamic pages, particularly those with content that don’t change too much or too often anyway.
Below is a very simple and generic cache script for PHP web pages which you can copy-paste and use almost instantly in your website. What it does is store an instance of the dynamically generated web page as an HTML file and it then counter checks with a predefined time period that you set whether to display the cached instance or to dynamically generate the page again. The longer the time period between dynamic generation, the greater the savings in terms of CPU usage and database queries.
1. First create a folder in your hosting account where you’ll be housing the cached data. In this example the cache folder is located at http://www.yourdomain.com/cache
2. Next, copy-paste the script below at the start of the PHP page you want cached. We are assuming here that the dynamically generated page is utilizing the GET variable “id”, such as: http://www.yourdomain.com/index.php?id=XXXX:
ob_start(); //turn on output buffering for PHP
//check if variable id is present and is an integer, if not, redirect to homepage
if ($_GET[‘id’]==”” or !is_numeric($_GET[‘id’]))
//absolute path to cache file. For simplicity the cached version of the page is saved as the ID number
$cachefile = $_SERVER[‘DOCUMENT_ROOT’].”/cache/$id.html”;
//duration before the cache is refreshed in seconds. Setting below is for a 3 day cache. Change as you see fit.
$cachetime = 259200;
// Serve from the cache if it is younger than $cachetime
if (file_exists($cachefile) && (time() – $cachetime
include($cachefile); //display the cache file
// if cache is display, exit the script
//if cache is not present or is too old, run the rest of the script……
//place a time stamp on the cache to easily check when a page was last cached…you can place this a meta variable in your HTML header i.e. <meta name=”date” content=”<?=$cachedate;?>”/>
$cachedate=date(“F d Y H:i:s”);
//THE REST OF YOUR PHP AND HTML CODE GOES HERE…………….
3. At the bottom of your PHP page, copy-paste the code below:
//define the cache file name
$cachefile = “cache/$id.html”;
// open the cache file for writing
$fp = fopen($cachefile, ‘w’);
// save the contents of output buffer to the file
// close the file
// Send the output to the browser
4. You’re done! Upload and update your PHP file.