How to create a simple and efficient PHP cache

When working on php websites made from scratch and without a framework, speed can often be an issue. Caching is extremely useful in order to speed up PHP webpages. In this article, I'll show you a super easy and efficient way to dynamically cache php pages that need to be faster.

Step one: Create the top-cache.php file

We need to create two files. Here’s the first one: Create a new file named top-cache.php and paste the code below in it.

$break = Explode('/', $url);
$file = $break[count($break) - 1];
$cachefile = 'cached-'.substr_replace($file ,"",-4).'.html';
$cachetime = 18000;

// Serve from the cache if it is younger than $cachetime
if (file_exists($cachefile) && time() - $cachetime < filemtime($cachefile)) {
    echo "<!-- Cached copy, generated ".date('H:i', filemtime($cachefile))." -->\n";
ob_start(); // Start the output buffer

So, what this code does? The first 5 lines create the cached file name according to the current php file. So, if you’re using a file named list.php, the cached file will be named cached-list.html.

Line 6 creates a $cachetime variable which determines the life of the cache.

Lines 9 to 13 are a conditional statement which look for a file named $cachefile. If the file is found, a comment is inserted (line 10) and the $cachefile file is included. Then, the exit statement stops the execution of the script and the file is sent to the client brother. Which means that if a static file is found, no php code is interpreted by the server.

Line 14 creates a buffer, if the $cachefile file isn’t found. That’s all for the top-cache.php file.

Step two: Create the bottom-cache.php file

Now, create a second php file, named bottom-cache.php and paste the code below in it.

// Cache the contents to a file
$cached = fopen($cachefile, 'w');
fwrite($cached, ob_get_contents());
ob_end_flush(); // Send the output to the browser

If a file named $cachefile isn’t found on your server, this code is executed and create the file, so next time the page will be called, the $cachefile static file will be served to the client browser instead of executing the whole PHP file.

Step three: Include cache files on your page

Now that you have created the two necessary files, you simply have to include them on the php page you wish to cache. As you probably guessed, the top-cache.php file must be included in the beginning of your php page and the bottom-cache.php at the end, as shown below:



// Your regular PHP code goes here


Now if you test the cache on a slow page, you’ll be amazed by how faster the page is. This easy cache is my favorite solution when working on “from scratch” PHP websites.

  • Mark

    Yeah you can save the file where ever you want obviously

  • Mark