How to create cache dynamic pages using PHP

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. 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. You may also like How to Create Dynamic XML Sitemap in PHP and How to add dynamic Active class on selected page using PHP.

PHP and HTML Code

<?php
$cache_ext = '.html'; 
$cache_time = 86400;  
$cache_folder = 'cache_files/'; 

$webpage_url = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] . $_SERVER['QUERY_STRING'];
$cache_file = $cache_folder . md5($webpage_url) . $cache_ext; 

if (file_exists($cache_file) && time() - $cache_time < filemtime($cache_file)) {
    ob_start('ob_gzhandler');
    readfile($cache_file);
    ob_end_flush();
    exit();
} else {
    ob_start('ob_gzhandler');
    
    ?>

    <html>
        <body>
            <h1>Demo file</h1>
        </body>
    </html>

    <?php
    if (!is_dir($cache_folder)) {
        mkdir($cache_folder);
    }

    $file = fopen($cache_file, 'w');
    fwrite($file, ob_get_contents());
    fclose($file);
    ob_end_flush();
}
?>

Leave a Reply

Your email address will not be published. Required fields are marked *