How to build a “static” PHP site

There are many times when you need to add a dynamic element to an otherwise static html website and reaching for a static site generator is just a bit heavy handed. Let’s look at how we can utilize PHP cacheing to build a “static” site.

Caveat: This is not a true static website, it will still require a PHP server, it will however mimic the speed performance of a static site. In a future post I will cover how to truly build a static site using PHP.

To accomplish this we will need two files, top-cache.php and bottom-cache.php, they should be included at the top and bottom respectively of any file you would like to be static.

top-cache.php

<?php

$url = $_SERVER["SCRIPT_NAME"];
$break = Explode("/", $url);
$file = $break[count($break) - 1];
$cachefile = "cached-" . substr_replace($file, "", -4) . ".html";
// Time cache is live in milliseconds, make this as long as you would like. The last number represents minutes, currently set to expire after 24hrs.
$cachetime = 1000 * 60 * 1440;

if (file_exists($cachefile) && time() - $cachetime < filemtime($cachefile)) {
    echo "<!-- Cached copy, generated " .
    date("H:i", filemtime($cachefile)) .
    " -->\n";
    readfile($cachefile);
    exit();
}
ob_start();
?>

bottom-cache.php

<?php
$cached = fopen($cachefile, 'w');
fwrite($cached, ob_get_contents());
fclose($cached);
ob_end_flush();
?>

To include these files:

<?php include "top-cache.php"; ?>
// your page code goes here
<?php include "bottom-cache.php"; ?>

Adding these to your file will generate a cache-[file].html file that will then be served in place of the php file as long as the cache time is still valid. The cache files are generated once a page is visited, so the entire site is not automatically generated but you can set the cache time as long as you want so once a page is generated it can be served statically for days, weeks, months, or longer.

It’s worth noting that you may want to put a git ignore in place to ignore these cache files. You could ignore all html files (*.html) or you could put your cache files in a directory by adding a directory to the $cachfile variable and ignore the directory.

This code was originally found here.