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:








function cachethis($filename, $seconds, $record = true){
 //If record is false, the page wont be saved..this is for debbuging.
 if (!$record){ return true; }
  //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";
   echo "<!-- End Cached -->";
   return false;
   //starting new cache file
   return $cachefile;
function endcache($cachefile){
 $fp = fopen($cachefile, 'w');
 fwrite($fp, ob_get_contents());
 // close the file


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.

$cachetime = 60; //seconds
$pagename = "theindex.html";

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

    <h1>This page was recorded on <?= date("H:i:s"); ?></h1><br>
    <label>This cache file will expire in <?= $cachetime; ?> seconds</label>
<?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.

One comment

  1. This script works perfect wrapping the index.php of a prestashop installation:

    Combining some rules in https://github.com/CleverCloud/varnish-examples/blob/master/prestashop.vcl works perfect .

    You only have to add the URL for shopping cart and avoid any cache when a POST request is made with:

    if ($_SERVER[‘REQUEST_METHOD’] != ‘GET’) {
    $ignore = true;

    Of course you have to check this ignore flag.

    Ask us any information if you want to implement it in a prestashop system: https://www.imaginacolombia.com


Leave a Reply

Your email address will not be published.