How to Create a Simple and Efficient PHP Cache
A guide to creating a PHP cache.
Join the DZone community and get the full member experience.
Join For FreeWhen 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 how to make a simple PHP caching system for your web pages.
What is Page Caching?
Page caching is a technique that seeks to create a collection of duplicate data when the original data is expensive to fetch or compute (usually in terms of access time).
As PHP is an interpreted programming language, the server has to execute the code each time a PHP page is requested. Depending on the complexity and length of the script, this operation can take time and demand lots of resources. If your website has a lot of traffic, it can really slow down your server and site.
If a web page is cached, the script will check if the related cache file exists. If it does, the static, cached file will be sent to the visitor’s browser. If not, a static version of the dynamic page will be created automatically the first time it is requested by a visitor.
By creating a static version of dynamic pages, the caching system saves a lot of server resources as the PHP script is only executed once, instead of it being executed each time the page is requested.
Cache files have a specific lifetime, which is set by the developer. If the defined lifetime is exceeded, the server will execute the PHP script and subsequently generate a new cached version of it.
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.
<?php
$url = $_SERVER["SCRIPT_NAME"];
$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";
readfile($cachefile);
exit;
}
ob_start(); // Start the output buffer
?>
What does this code do? The first five lines create the cached file name according to the current PHP file. So, if you’re using a file named list.php
, the web page created by the page caching will be named cached-list.html
.
Line six creates a $cachetime
variable, which determines the life of our simple cache (Cachefile time).
Lines nine to thirteen are a conditional statement which looks for a cache file named $cachefile
. If the file is found, a comment is inserted (line ten) and the $cachefile
file is included. Then, the exit
statement stops the execution of the script and the file is sent to the client browser. This means that if a static file is found, no PHP 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 another new PHP file, named bottom-cache.php
and paste the code below in it.
<?php
// Cache the contents to a cache file
$cached = fopen($cachefile, 'w');
fwrite($cached, ob_get_contents());
fclose($cached);
ob_end_flush(); // Send the output to the browser
?>
If a cached file named $cachefile
isn’t found on your server, this code will be executed and will create the cache file itself.
As a result, next time the page will be requested, 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 at the beginning of your PHP page and the bottom-cache.php
at the end, as shown below:
<?php
include('top-cache.php');
// Your regular PHP code goes here
include('bottom-cache.php');
?>
Now if you test the cache on a slow page, you’ll be amazed by how faster the page is. This simple PHP caching system is my favorite solution when working on PHP websites from scratch.
Frequently Asked Questions
What is OpCode Cache?
An OpCode cache is a performance-enhancing extension that caches the result of the PHP code compilation to bytecode. Throughout PHP’s lifetime, there have been a number of OpCode caches available, mostly depending on the used PHP version.
How Do I Enable OpCode Cache?
As available OpCode caches depend on the PHP version used on your server, please get in touch with your web hosting provider to see how to enable OpCode caching on your site.
Did this method work for you? Comment and let us know!
Published at DZone with permission of Jean-Baptiste Jung, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments