If your website receives a good amount of traffic every day and your web pages are loading slow, you might want to consider implementing some sort of caching mechanism on your website to speed up page loading time. Because as we all know that each client-server request consists of many queries, loops, calculations, database queries etc. these all add up to processing time, which eventually increases page loading time. The simplest way to avoid all these is to create cache files and store them in a separate directory, which can later be served as fast loading static pages instead of dynamically generated pages.
There are several other PHP cache engines such as APC, Xcache or OPcache to boost your application performance, but they all work quite differently if you are curious; you can always find plenty of articles and tutorials written about them on the web. But here you’ll learn the simplest way of caching PHP pages, and that is using PHP’s core output Buffer and Filesystem, combining these two functions we can have a magnificent caching system..
PHP Output buffer :— It interestingly improves performance and decreases the amount of time it takes to download, because the output is not being sent to browser in pieces but the whole HTML page as one variable. The method is insanely simple take a look at the code below :
First line ob_start() turns the output buffering on, which means anything after this will be stored in the buffer and to retrive the contents of the output buffer we simply call ob_get_contents(). The ob_end_flush() at the end of the code turns buffering off.
PHP Filesystem :— is a also a part of the PHP core, which allow us to read and write the file system.
As you can see the first line of the code fopen() opens the file for writing, the mode ‘w’ places the file pointer at the beginning of the file and if file does not exist, it attempts to create one. Second line fwrite() writes the string to the opened file, and finally fclose() closes the successfully opened file at the beginning of the code.
Now you should be pretty clear about PHP output buffer and filesystem, we will use both methods to create our simple PHP caching system. Please have a look at the picture below, the flowchart gives you the basic idea of our cache system.
The cycle starts when a user requests the content, the script simply checks and outputs the cache copy of requested page, if it doesn’t a new copy is created and sent to the browser.
Below is the full example of PHP caching system, you can examine, copy it into your PHP project and play with code, it should work as expected. You can modify the cache expire time, cache file extension, ignored pages etc. to suit your needs.
Here’s quick points to help you understand the code: