All TalkersCode Topics

Follow TalkersCode On Social Media - A Social Media Network for developers Join Now ➔

Cache Dynamic Pages Using PHP

Last Updated : Jul 1, 2023

IN - PHP | Written & Updated By - Amruta

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

$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)) 
 echo '<!-- cached page - '.date('l jS \of F Y h:i:s A', filemtime($cache_file)).', Page : '.$webpage_url.' -->';

// Your Webpage Content Starts

<h1>Your Webpage Content</h1>

// Your Webpage Content Ends 

if (!is_dir($cache_folder)) 

$file = fopen($cache_file, 'w');
fwrite($file, ob_get_contents()); 

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.

I hope this tutorial on cache webpages php helps you and the steps and method mentioned above are easy to follow and implement.

Author Image About Amruta

Amruta is an Experienced web developer with 4 years for experience she completed her master's with MCA and passionate about programming Languages for creating technical contents like HTML, CSS, JavaScript, Java, Python, PHP, jQuery.

Follow Amruta On Linkedin 🡪