Want To Be A Blogger  →  Start A Blog  →  Increase Traffic  →  Make Money Online  →  Recommended Things

Cache Dynamic Pages Using PHP

Thursday, Sep 28, 2017

Tags:- PHP


In this tutorial we will show you how to cache dynamic pages using PHP. PHP cache is based in a set mechanism.It starts when user request the webpage we check if that cache webpage is present in our cache directory if yes then we display that cache page and if not we create a cache webpage and save it in our cache directory and then send that webpage to browser for display.The reason behind to use caching is to reduce page load time.


Cache Dynamic Pages Using PHP


To Cache Dynamic Pages It Takes Only One Step:-

  1. Make a PHP file and implement caching mechanism


Step 1.Make a PHP file and implement caching mechanism

We make a PHP file and save it with a name cache.php

<?php
$cache_ext = '.html'; //file extension
$cache_time = 86400;  //Cache file expire time (24 hour = 86400 sec)
$cache_folder = 'cache_files/'; //Cache files folder 

$webpage_url = 'http://'.$_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] . $_SERVER['QUERY_STRING'];
$cache_file = $cache_folder.md5($webpage_url).$cache_ext; // creating unique name for cache file

if (file_exists($cache_file) && time() - $cache_time < filemtime($cache_file)) 
{ 
 ob_start('ob_gzhandler'); 
 readfile($cache_file); 
 echo '<!-- cached page - '.date('l jS \of F Y h:i:s A', filemtime($cache_file)).', Page : '.$webpage_url.' -->';
 ob_end_flush(); 
 exit(); 
}
else
{
ob_start('ob_gzhandler'); 

// Your Webpage Content Starts
?>

<html>
<body>
<h1>Your Webpage Content</h1>
</body>
</html>

<?php
// Your Webpage Content Ends 

if (!is_dir($cache_folder)) 
{ 
 mkdir($cache_folder);
}

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

In this step we first set all the variable values required to create cache file we set file extension, expire time, cache folder, unique name for every cache file.When user request for webpage we check if that webpage is present in 'cache_file' directory and if it is present we send that page to the browser to display and if it is not present we use ob_start to start the output buffer then our webpage content and then check if 'cache_file' directory is present if not create that directory then create that webpage cache and close the output buffer.



Thats all, this is how to cache dynamic pages using PHP.You can customize this code further as per your requirement. And please feel free to give comments on this tutorial.

Subscribe Our Newsletter And Get Tutorials And Offers Via Email

About Me


Hello, My Name is Mudit Jain. I am a Web Developer, Professional Blogger and Digital Marketer from India. I am the founder of TalkersCode. I started this blog in february 2015 to help web developers & bloggers by providing easy and best tutorials, articles and offers for web developers and bloggers.