Simple PHP File Cache

In this article, you will learn simple file caching process using PHP. Instead of establishing the server connection every time on requesting the same page, we can store a copy of that page in an external file. Once this will get stored, we can call this 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 name '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

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( )
    function stopBuffering( )
        $fp     =   fopen($this->file_name, 'w'); 
        fwrite($fp, ob_get_contents()); 
    function check()
        return(file_exists($this->file_name) && (time() - $this->cache_time < filemtime($this->file_name)));

In the above example -
ob_start() - This function is used to turn on the output buffering.
ob_get_contents() - This function return the contents of output buffer.
ob_end_flush() - This function is used to turn off the output buffering.

This is the main file, that we will call on the browser. In this file, first we have included the 'cache.php' file and then, check the already buffered data. It the condition is true, then display the buffered page on the browser otherwise start buffering and display the page.

2. index.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
            <title>Cache this page</title>
                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. 
// stop buffering

Read more articles

General Knowledge

Learn Popular Language