Simple PHP File Cache

In this article, 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.





Simple PHP File Cache

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


<?php
class CachingClass
{
    var $cache_time  =   null;
    var $file_name   =   null;
    function __construct( $file_name, $cache_time = 0 )
    {
         $this->cache_time =  ( $cache_time > 0 ) ? $cache_time : (300 * 60);
         $this->file_name  =  $file_name;
    }
    function startBuffering( )
    {
        ob_start();
    }
    function stopBuffering( )
    {
        $fp     =   fopen($this->file_name, 'w'); 
        fwrite($fp, ob_get_contents()); 
        fclose($fp);
        ob_end_flush();
    }
    function check()
    { 
        return(file_exists($this->file_name) && (time() - $this->cache_time < filemtime($this->file_name)));
    }
}
?>




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

<?php
// File to store cache
$cachefile = "cache/storecache.php";
// Include cache class
include_once 'cache.php';
$buffer_object = new CachingClass($cachefile);  
// check already buffered data
if( $buffer_object->check() ) {  
    include_once $cachefile; 
} else { 
    // start buffering
    $buffer_object->startBuffering();
?>
    <html>
        <head>
            <title>Cache this page</title>
        </head>
        <body>
            <p>
                Lorem Ipsum is simply dummy text of the printing and typesetting industry.
                Lorem Ipsum has been the industry's standard dummy text ever since the 1500s,
                when an unknown printer took a galley of type and scrambled it to make a type specimen book.
                It has survived not only five centuries, but also the leap into electronic typesetting, 
                remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset
                sheets containing Lorem Ipsum passages, and more recently with desktop publishing software
                like Aldus PageMaker including versions of Lorem Ipsum. 
            </p>
        </body>
    </html>
<?php
} 
// stop buffering
$buffer_object->stopBuffering();
?>




Related Articles

How to display PDF file in PHP from database
PHP remove last character from string
PHP calculate percentage of total
PHP code to send SMS to mobile from website
PHP program to reverse a string without predefined function
How to read CSV file in PHP and store in MySQL
Create And Download Word Document in PHP
PHP SplFileObject Standard Library
Simple File Upload Script in PHP
Sending form data to an email using PHP
Get Visitor's location and TimeZone
How to use google map street view api on webpage
How to add google maps multiple markers
How to add google map on your website with marker
Create pie chart using google api
Driving route directions from source to destination using HTML5 and Javascript
Calculate the distance between two locations using PHP
PHP rating system




Read more articles


General Knowledge



Learn Popular Language