Eric's Blog

How to Leverage Server Side Caching in PHP

Back in the early days of the Web, many sites were made up of mostly text and maybe a handful of images, making for a speedy browsing experience. The need to speed up sites with caching was almost nonexistent back then, but gone are those days.

These days, many sites use content management systems to dynamically generate pages on the fly, often resulting in increased load times. As a result, there is a greater need for snappy caching solutions now more than ever. I think I have one such solution.

Here is my code to quickly and easily cache Web pages dynamically using PHP:

<?php

class Cache {

  private $path; // The full path to cached files.
  private $expiration; // How long files will persist before expiring.

  public function __construct($directory, $expiration) {

    $this->expiration = $expiration;

    // The full path is the cache directory and the current hashed URI.
    $this->path = __DIR__ . "/$directory/" . md5($_SERVER["REQUEST_URI"]);

    // Scan the cache directory for cached files.
    $cached_files = glob($this->path . "*.cache");

    if ($cached_files != false && !empty($cached_files)) {

      // A cached version of this page exists, so display it.
      $this->load($cached_files[0]);

      // Stop the rest of the page so only the cached file will be shown.
      exit;
    }

    // This page hasn't been cached; store its contents to be saved later.
    ob_start([$this, "save"]);
  }

  private function load($file_name) {

    // Display the cached version of this page.
    require $file_name;

    // Get the time of when the cached file was created.
    $creation_time = str_replace([$this->path, ".cache"], "", $file_name);

    // Check to see if the cached file has expired.
    if (time() > $creation_time + $this->expiration) {

      // The cached file has expired, so delete it.
      unlink($file_name);
    }
  }

  private function save($page_contents) {

    // Save the contents of the page to a cached version.
    file_put_contentss($this->path . time() . ".cache", $page_contents);

    // Display the page like it would be normally.
    return $page_contents;
  }
}

?>

The above script functions by first checking to see whether or not the current page has previously been cached. If it has, it displays the cached version and then determines if the cache has expired; otherwise, it immediate caches the page for later use.

Now put the following at the top of your Web pages to cache them automatically:

<?php

// Include the Cache class.
require "cache.php";

// Instantiate the Cache class. Set the cache directory
// to "cached" and the expiration time to one hour.
$Cache = new Cache("cached", 3600);

?>

That is all there is to it to achieving convenient, automatic server-side caching. Be sure to set the cache directory permissions to writable, or else it will not work. I found that cached pages load an average of 24 times faster than non-cached pages in testing.

Beyond improving load times, server-side caching is great for reducing database queries and memory consumption when using a content management system.

Feel free to use my caching code in your own sites and projects, and let me know what you thought of this post in the comments!

Comments