Simple PHP File Cache
How does PHP store data in cache
In this exercise, you will learn about a simple file caching process using PHP. Cache is important because it improves the efficiency of data retrieval. It is a reserved storage location that collects temporary data to help websites, browsers, and apps load faster.
As we know, PHP is an interpreted programming language, which means the server has to execute the code each time a PHP page is requested. Instead of establishing a server connection every time we request the same page, we can store a copy of that page in an external file. Once this gets stored, we can call it from the stored location. This will reduce the server loading time and load the web page much faster.
In this example, we are using the Output Buffer to cache the requested file. For this, first create a folder 'cache' in the same directory where you will place the 'index.php' file. After that, create two files and copy and paste the following code.
1. cache.php
In the above example -
ob_start()- This function activates output buffering.
ob_get_contents()- This function returns the contents of the output buffer.
ob_end_flush()- Use this function to disable output buffering.
This is the main file, that we will call in the browser. In this file, first we include the 'cache.php', and then we check the already buffered data. If the condition is true, then display the buffered page on the browser, otherwise, start buffering and display the page.
2. index.php
need an explanation for this answer? contact us directly to get an explanation for this answer