How to cache PHP code and how does PHP cache mechanism works? At the end you will learn on how to create a PHP caching mechanism and always serve your website with fast loading pages.

Now you have designed a beautiful eye catching website that users will definitely like. But you see there is no good amount of traffic flowing in, because your website is a dynamic page which is taking lot of time for a server to process, execute, transfer and finally render it in a user’s browser.

PHP Dynamic Page Creation

So, processing time is the main reason for your slow website and that may leave users with bad experience. An ideal recommended Website Load Time should be around 2 to 5 seconds. To achieve that with your dynamic PHP page, we are implementing some sort of caching mechanism on your website to speed up page loading time. So, we can serve fast loading static page using our cache system.

After using PHP Caching System

The simplest way to do is to create cache file of each page of your website and store them in a separate directory, which can later be served as fast loading static pages instead of dynamically generated slow pages.

PHP Caching (Output Buffer + File System):

Now the cache technique we use here is by combining PHP’s Output Buffer and Filesystem. Using them we can have a wonderful caching system and create wonders. The Filesystem and Output Buffer functions are both part of the PHP core. There is no additional installation needed to use these functions. You can see how our caching system works as given below.

Un cached vs Cached Request
PHP Caching System Flow Chart

PHP Output Buffer:

Now let us understand how Output Buffer works.

First line ob_start() turns the output buffering on, which means anything after this line will be stored in the buffer

<?php
ob_start(); // Turns on output buffering
?> 

We use ob_get_contents() to retrieve the contents of the output buffer.

<?php
ob_get_contents(); // Stores the contents of the buffer
?>

We use ob_end_flush() at the end of the code which turns off buffering.

<?php
ob_end_flush(); // It ends or turn off the buffering
?>

PHP File System:

Here we use filesystem functions to access and manipulate the filesystem.

Very first function we use is fopen to open a file to write content and in the below code 'w' is a mode which is used to create a file if it doesn’t exist.

<?php
$fp = fopen('/path/file.txt', 'w');  //open file for editing
?>

Next we use fwrite to write contents into the file.

<?php
fwrite($fp, 'write this text'); //write to the file
?>

And finally we use fclose to close the open file after we finish writing.

<?php
fclose($fp); //Close the file after editing
?>

Now we will combine both PHP’s Output Buffer and Filesystem to build an exceptional PHP page caching system.

So, now we will create two files, one is start-cache.php and another one is end-cache.php. By the end of this post you will get to know why did we create two files namely start-cache.php and end-cache.php

Cache PHP Code

1. Create the start-cache.php file:

<?php

$cache_ext 	= '.html'; //Cache file extension
$cache_time 	= 3600;  //Cache file expiry in sec (1 hr = 3600 sec)
$cache_folder 	= 'cache/'; //Folder to store Cache files in

$dynamic_url 	= 'http://'.$_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] . $_SERVER['QUERY_STRING']; // Requested full dynamic page URL

$cache_file 	= $cache_folder.md5($dynamic_url).$cache_ext; // Construct a cache file

if (file_exists($cache_file) && time() - $cache_time < filemtime($cache_file)) { //Check Cache file exist and it's not expired.
	ob_start('ob_gzhandler'); //Turn on output buffering with "ob_gzhandler" for compressed page with gzip.
	readfile($cache_file); //Read Cache file
	echo '<!-- cached page - '.date('l jS \of F Y h:i:s A', filemtime($cache_file)).', Page : '.$dynamic_url.' -->';
	ob_end_flush(); //Flush and turn off output buffering
	exit(); //No need to proceed further, exit the flow.
}

ob_start('ob_gzhandler'); //Turn on output buffering with gzip compression.

?>

Let me explain what does that above code do. Firstly we create file structure by providing file extension and followed by the expiry time of a cache file and the folder in which the cache file will be saved to or stored.

And the very next step we do is to construct a cache file into cache folder by using URL of the dynamic page you want to cache and implement its file name with md5 hash. So, the cache file we create looks something like this 2e3fe7440b17262a6576b9848d0a10f8.html in the cache folder after successful cache.

Now our script checks for cache file if exists in the cache folder and if the file is not expired. And if it is not expired then that cache file is served to the user and ends the script. Here as our intention is to serve the cache file faster, we are using gzip compression with 'ob_gzhandler' which will send entire file in a single request instead of sending bytes of the code one after other which speeds up this entire process.

Next if the cache file does not exist or expired then the code should initiate to create one. To do so, we start the Output buffer with ob_start('ob_gzhandler'); and anything after this line in the script will capture your dynamic page contents. And other things after this is handled by end-cache.php file which is given below.

2. Create the end-cache.php file:

<?php

if (!is_dir($cache_folder)) { //Create a new folder if doesn't exist
    mkdir($cache_folder);
}

$fp = fopen($cache_file, 'w');  //Open file for writing
fwrite($fp, ob_get_contents()); //Write contents of the output buffer in Cache file
fclose($fp); //Close file pointer

ob_end_flush(); //Flush and turn off output buffering

?>

Now the above script will create a cache folder using filesystem functions if the cache folder doesn’t exist. To create the cache folder the script uses folder name from settings provided at the beginning of the code. Next the script opens cache file to write contents of the dynamic page and if the cache file doesn’t exist we create one with 'w' mode in the script. Using fwrite we write contents into the cache file and finally we close that open cache file with fclose and end the output buffer with ob_end_flush();

3. Include created Cache PHP files in your webpage:

Now that you have created two files, you simply have to include them in the page you wish to cache. So, here the files which we made you create are start-cache.php and end-cache.php. During explanation you should have understood that we will include first file at the beginning of the code and the other file at the end of that code. You can see the example of including files in the below code.

<?php

include('start-cache.php'); 

?>

<!-- Anything between these lines will be cached -->
<!-- Your Html/PHP code goes here -->

<?php

include('end-cache.php');

?>

You have just finished making a cache script which will now load a slow PHP page incredibly faster.