Cache technique in PHP

In this example we will check the actual optimization using a small script in PHP to generate a cache file using code, although there are many ways and techniques, today we will analyze one of them.

The goal is to create pure and static HTML files, understand that we refer to pure and static those pages whose content remain unchanged and formatted with html tags. On the other hand, a dynamic content page is one that from PHP scripts can eventually contain: long and complex processes, interaction and queries based on data, among other things, which finally are what condition and present their content, including they may vary between one request and another; so the goal is to optimize a dynamic content page but once created such content does not need constant generation of it.

If we need that the content is one hundred percent in real time and that constantly varies, the cache in this case, is not a recommended or useful option, the intention is to “cache” pages with contents that can in some way or another take N seconds in cooling and that in different requests remains unchanged for some time.

When generating HTML files we will be protecting the unnecessary waste of server resources, and obviously we optimize the overall performance: resources vs. results, understand that by consuming HTML directly we would be achieving: fewer queries to Database, less processes, finally this will be reflected in less overall wear from our web server.

To optimize we must have an initial metric

Well, it is what we have to do, firstly “measure” the execution time of a script without a cache, it can be a whole page or part of the script (it is understood that when we say pages we refer to the individual document, because many people could refer to it erroneously as a page to a site).

To have an initial metric we will use the following code.

If it’s a page with static content, it does not make sense to use this caching technique.

$Start= microtime(true);  //At file Start

Then we use all the code present on the page, be these: PHP, HTML, CSS and / or Javascript, depending on the project.

And at the end of everything we will place the following.


/*—————-Fin Código———————–*/

$final= microtime(true);  //At file ending

echo  “Time: “. number_format($end-$start,4).”  seconds.”;


Now we will have documented the initial execution time, we should save that information as a basis for the analysis.

Next we will create two new files.


$start= microtime(true); //at file start

$url = $_SERVER[“SCRIPT_NAME”]; //we get the name the url and current file names

$break = explode(‘/’, $url); //we divide the unions by / and we get a data matrix

$file = $break[count($break) – 1]; //we get the real name of the file

$cachefile = ‘cached-‘.substr_replace($file ,””,-4).’.html’; //we create a new name for the cache, this will be HTML to optimize resources

$cachetime = 900; //we set the duration time of the cache in seconds | 900/60 = 15 minutes

// Serve from the cache if it is more current than $cachetime

if (file_exists($cachefile) && time() – $cachetime < filemtime($cachefile)) {

echo “<!– Generated cache copy “.date(‘H:i’, filemtime($cachefile)).” –>\n”;


$final= microtime(true); //at file end

echo “<div>New time: “. number_format($end-$start,4).” seconds.</div>”;



ob_start(); // Create output buffer


// Cache the contents of the file

$cached = fopen($cachefile, ‘w’); //takes the name of the cache file that we created in topo_cache if it does not exist or if it has already passed its useful life

fwrite($cached, ob_get_contents()); //write all the contents of the current file


ob_end_flush(); // Send the browser

This file top_cache.php should be included in the first line of my page to “cache” and bottom_cache.php at the end.

 <?php  include "top_cache.php"; ?>

Here goes the code PHP, HTML, css, etc.

 <?php include "bottom _cache.php"; ?>

In our tests the improvement was noticed at 50% but strangely just after the third call to the cached page; this does not work correctly when there is paging in between, because this is based on the name of the file and when it is pagination, the name of the page remains the same only with different parameters, unless we use friendly url in which case each Pagination could be a different name, although with a little patience maybe and we find a solution to that.

You might also like…

A look at Scriptcase 9

In a daily basis this tool has given me great satisfaction, and very good and fast results in terms ...

Deep Data: Is it possible when you’re non-profit?

Evan Liebovitch talks about deep data and how to document the needs of a non-profit while using Scri...

Deep Data: Creating Powerful Large Systems

Creating powerful large systems to support business processes in a cost-effective and accessible man...

Comment this post

Get new posts, resources, offers and more each week.