How to create Cache for Dynamic webpages in PHP

 

Caching is a very important approach for the websites, those requires  high traffic. It reduces the load on server and gives quick response time for loading the content of a webpage.

What is web caching? How it works?
 

Web Caching is nothing but storing (cached) webpages in the disk for a period of time to respond for requests of user(s). 

In PHP, dynamic pages will be created and served content based on the request (Eg. query string). In this way multiple requests may reached server for multiple users for the same content. The server has to process every request and serve the content, which reduces the performance of the server for loading the pages.

Now Web caching will fix this issue by creating cache webpage for unique request to be available for a period of time using OB (Output Buffer).

Any user requested a content, server invoked the cache webpage. If it is available in the disk, then loads the content of cached webpage. If not, Cached webpage will be created and served. We can store these cache files in any directory (eg. cache) for easy access.

Let's work with it:

1. Create cache_top.php file with the following code.

<?php

    $pageId = 1;
    $cache_folder = '../cache/';                                         //Cache files folder

    $cachefile = $cache_folder.'cached-'.$pageId.'.php';
    $cachetime = 18000;            // 5 hr * 60 min * 60 sec

    // Serve from the cache if it is younger than $cachetime

    if (file_exists($cachefile) && time() - $cachetime < filemtime($cachefile)) {

        echo "<!-- Cached copy, generated ".date('H:i', filemtime($cachefile))." -->\n";

        readfile($cachefile);

        exit;

    }

    ob_start(); // Start the output buffer

?>

2. Now create cache_bottom.php file with the following code.

<?php

    // Cache the contents to a cache file

    $cached = fopen($cachefile, 'w');

    fwrite($cached, ob_get_contents());

    fclose($cached);

    ob_end_flush(); // Send the output to the browser

?>

Finally integrate both files with our HTML content as follows.

<?php require_once("cache-top.php"); ?>

    /* HTML CONTENT GOES HERE */
    
<?php require_once("cache-bottm.php"); ?>

Everything has done!!!


Latest
Previous
Next Post »
Related Posts Plugin for WordPress, Blogger...