How to create a simple file caching system in php
It is very easy to build a cache system in PHP and for those that are not familiar with a cache system,a cache system is just a system that saves dynamically generated files in a system for easy retrieval.
For instance, when you go to a website with a link like this example.com?get=9, there is a likelihood that the number 9 is the database table id for a particular content you are looking for, so the website script receives your url query, connect to the database , receives your information in an array , process the array and then return the data back to your browser, now all of this will eat up loading time because of the different connections and processing it is had to undergo.
So instead of having to go through this process each time someone requests a page, the webpage is set to process the page the first time (as i stated above), then it stores the returned output to a file on the server ,so that anytime that same page is requested, no processing needs to be done, it just retrieves the already processed page and serves it to you like a "microwaved meal".
A browser uses this same system for storing files of websites you visit often.
There is a downside, if the database data that the cached page serves undergoes a change , the cached page might not be able to reflect it, so caching is not good for pages that change a lot like news feed, but could be used for blog posts since they rarely undergo any change.
Now, here is how it is done
STEP 1; Create page to be cached,
lets name it love.html
LOVE IS A BEAUTIFUL THING
The above just represents a piece of data that needs to be saved in a cache. It could be html but to avoid complexity, let's use a simple text like the above
STEP 2: Activate Output Buffering using ob_start();
Output buffering is just a way of storing the output of a page in php.
So lets add it to the content above
<?php
ob_start();
?>
LOVE IS A BEAUTIFUL THING
Now that ob_start() has been added to the top of the content, it means subsequent content of that page after the ob_start() is being stored somewhere. You'll see where it's been stored in the next step
STEP 2: Store the file in cache
Before you do this, please create a folder and name it cache, it can be anything you want but for the sake of this tutorial, just name it cache.
After that, create a function to give the folder a unique hashed name to avoid complexities of url structure and then cache the content.
The below function is just for naming
function cacheName(){
$url = preg_replace('/^\/[a-zA-Z0-9_]+\//i','',$_SERVER['REQUEST_URI']);
$url = md5($url);
$cache_folder = 'cache';
$filename = "$cache_folder/$url.html";
return $filename;
}
The below function performs the caching operation
Function cacheGET()
{
$cachefile = cacheName();
$fp = fopen($cachefile, 'w');
fwrite($fp, ob_get_contents());
fclose($fp);
ob_end_flush();
}
Now lets add the function to our codes
<?php
function cacheName(){
$url = preg_replace('/^\/[a-zA-Z0-9_]+\//i','',$_SERVER['REQUEST_URI']);
//Hash the cache filename(THIS IS IMPORTANT TO REMOVE SEO SLASHES)
$url = md5($url);
$cache_folder = 'cache';
$filename = "$cache_folder/$url.html";
return $filename;
}
Function cacheGET()
{
$cachefile = cacheName();
// open the cache file "cache/home.html" for writing
$fp = fopen($cachefile, 'w');
// save the contents of output buffer to the file
fwrite($fp, ob_get_contents());
// close the file
fclose($fp);
// Send the output to the browser
ob_end_flush();
}
ob_start();
?>
Love is a beautiful thing
<?php cacheGET(); ?>
As you can see, I first added the functions to be used above the content to be cached , then I added ob_start(); meaning every output that comes after it should be stored somewhere, then after the content content, meaning the content is being stored , then i called the function cacheGET(); , which uses retrieves the output by using `ob_get_contents()' to retrieve the buffered contents and then write it to the named file using fwrite();
We are not done yet, we have only been able to store the file, we can not serve the file yet in case a user request for this page. So this is how it goes.
Serving the final script
To serve the file, we need two more functions cache_check() to check if the file exists and then cacheSHOW(); to serve the file if it exists.
Function cacheSHOW()
{
if (cache_check())
{
include(cacheName());
exit();
}
}
function cache_check()
{
$cachefile = cacheName();
if (file_exists($cachefile)) {return true;}
else {return false;}
}
Now it is time for us to add this functions to our previous codes and then have a finally script that can cache and serve scripts .
Final Scripts
<?php
function cacheName(){
$url = preg_replace('/^\/[a-zA-Z0-9_]+\//i','',$_SERVER['REQUEST_URI']);
//Hash the cache filename(THIS IS IMPORTANT TO REMOVE SEO SLASHES)
$url = md5($url);
$cache_folder = 'cache';
$filename = "$cache_folder/$url.html";
return $filename;
}
Function cacheGET()
{
$cachefile = cacheName();
// open the cache file "cache/home.html" for writing
$fp = fopen($cachefile, 'w');
// save the contents of output buffer to the file
fwrite($fp, ob_get_contents());
// close the file
fclose($fp);
// Send the output to the browser
ob_end_flush();
}
Function cacheSHOW()
{
if (cache_check())
{
include(cacheName());
exit();
}
}
function cache_check()
{
$cachefile = cacheName();
if (file_exists($cachefile)) {return true;}
else {return false;}
}
cacheSHOW();
ob_start();
?>
Love is a beautiful thing
<?php cacheGET(); ?>
In the final script, you can see that I called the cacheSHOW function before the content to be cached so that it can show the content if it is cached already and then terminate the script with the exit command in the function to avoid double outputs which will make the caching a meaningless effort.
Feel to use and run the final script , more so, the content Love is a beautiful can be replaced with anything other content which can be html or xml codes .
Posted on Utopian.io - Rewarding Open Source Contributors
Thank you for the contribution. It has been approved.
You can contact us on Discord.
[utopian-moderator]
Hey @akintunde I am @utopian-io. I have just upvoted you!
Achievements
Suggestions
Get Noticed!
Community-Driven Witness!
I am the first and only Steem Community-Driven Witness. Participate on Discord. Lets GROW TOGETHER!
Up-vote this comment to grow my power and help Open Source contributions like this one. Want to chat? Join me on Discord https://discord.gg/Pc8HG9x