Easy way to cache your not so dynamic pages with PHP

So your website has now thousands of visitors? Well, congratulations… but your system processor is probably on a huge load if you haven’t added any caching options. Here is PHP to the rescue.

Add this two functions to any php file and call it with include on all the pages you need to catch:

 

 

 

 

 

 

//functions.php

function cachethis($filename, $seconds, $record = true){
 //If record is false, the page wont be saved..this is for debbuging.
 if (!$record){ return true; }
 else{
  //using stored page
  $cachefile = "cache/".$filename;
  if (file_exists($cachefile) && (time() - $seconds < filemtime($cachefile))){
   echo "<!--Cached ".date('jS F Y H:i', filemtime($cachefile))."-->\n";
   include($cachefile);
   echo "<!-- End Cached -->";
   return false;
  }else{
   //starting new cache file
   ob_start();
   return $cachefile;
  }
 }
}
function endcache($cachefile){
 $fp = fopen($cachefile, 'w');
 fwrite($fp, ob_get_contents());
 // close the file
 fclose($fp);
 ob_end_flush();
}

 

Now every time you need to generate cache for a page, you can add this to save the generated php content into a cache file that will be readed the next time instead.

<?php
//index.php
include("libs/functions.php");
$cachetime = 60; //seconds
$pagename = "theindex.html";
?>

<?php if ($cachefile = cachethis($pagename, $cachetime)){ ?>

  <body>
    <h1>This page was recorded on <?= date("H:i:s"); ?></h1><br>
    <label>This cache file will expire in <?= $cachetime; ?> seconds</label>
  </body>
  
<?php endcache($cachefile); }//cache end ?>

 

The code will save a copy of the generated page (wrapped in the ‘if’ statement) the first time the page is run or if the previous file is too old. If the desired page exists and its time valid, it will display the contents of the stored file instead.

Leave a Reply

Your email address will not be published.