PHP Cache for Dynamic Web Pages

by Vincy. Last modified on July 11th, 2022.

Caching a dynamic web page is very important. When developing a website using PHP, the cache is often overlooked. Cache helps to increase the speed of the website response. In the web, nanosecond performance improvement can make wonders.

If your site depends on search engine traffic, then the cache should be your foremost priority. Google considers page speed as a critical aspect of a website.

In this PHP tutorial, I will create a simple cache mechanism without using any frameworks. The cache will be custom-built using PHP code and that too with few lines of code.

Since it is simple do not underestimate the code, it is very efficient. I am using it on one of my live websites with great results.

Cache Approach

We can achieve effective cache mechanism using a two-step process as below.

  1. “htaccess” to check if a cached file is ‘not’ present, invoke a PHP page.
  2. Invoked PHP page does the caching and sends the response.


Step 1: .htaccess to check for Cache file

Cache folder should not be separate as often you see in many systems. It is not necessary. In you see WordPress, if you add a plugin like ‘WP Super Cache’ it creates a separate folder to store the cache files.

IMPORTANT: I recommend a different approach, store the files on the disk with respect to the URL location as if the files are directly served from the disk.

Now design the .htaccess RewriteRule in such a way that it should be a fallback. That is, if the physical file is not present in the disk with respect to the request location, then invoke the dynamic PHP file.

# Checks if the file is physically NOT present
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([a-z0-9-]+)+/([a-z0-9-]+)\.html$	/controller.php?partA=$1&partB=$2 [L]

The above rewrite rule is written for URLs with extension as “.html”. If you do not have this extension, then you need to remove that extension part and it will work as planned.

This rule checks if the cached page is present in the given location if not invokes the controller.php file. There we will forward to the respective dynamic page based on the arguments.

Step 2: Cache the Dynamic Page

When the dynamic PHP file is invoked, all you need to do is cache the file in the disk and send the response. So the first time, the “htaccess” will invoke the PHP page and it will create the cache file.

Then afterward, this dynamic PHP file will not be invoked till the cache file is evicted from the disk.

Create a file and name it cache.php and put the following code. Then include this cache.php file on top of the dynamic page whose content you want to be cached.


function cache_page($content) {
	//path location where the cache file should be placed
	if(false !== ($f = @fopen($fileName, 'w'))) {
      fwrite($f, $content);
    return $content.'';
// Start the output buffer for cache with callback on buffer-flush

Now let us see how to include this file in a dynamic page. Consider that we are caching the contents of the PHP page article.php


//here you have all the dynamic part of page
//like for example, you may access a database
<!-- @ <?php echo date("c"); ?> -->

So how does it work, we are using the callback option available. We start the output buffer and on buffer-flush, we are declaring a callback function ‘cache_page’ to be called.

So when the content is ready to be served, this method will be called and we write the content to the disk and add a line to say that it is fresh and continue with the response.

Did you notice the last line in both cache.php and article.php? Those are lines included using which we can verify if the rendered page is cached. If cached, when it was cached.

Right click and see the view source when the page is rendered and you can find the cache time and also if the page is served fresh.

Cache eviction and expiry is not handled. It will be covered in a separate tutorial.

I am using this approach on my site and it has given great results. If you are using ‘Google Webmaster Tools’ (Search Console), there you can see the average response time.

After I implemented this cache mechanism, I got 50% improvement in the response time. Try this and let me know.

Written by Vincy, a web developer with 15+ years of experience and a Masters degree in Computer Science. She specializes in building modern, lightweight websites using PHP, JavaScript, React, and related technologies. Phppot helps you in mastering web development through over a decade of publishing quality tutorials.

Comments to “PHP Cache for Dynamic Web Pages”

  • Unyime Udoh says:

    I did not understand this line of code
    RewriteRule ^([a-z0-9-]+)+/([a-z0-9-]+)\.html$ /controller.php?partA=$1&partB=$2 [L]

    Firstly, i wonder where the controller.php script is located.

    I tried it, and it did not work for me

    • Vincy says:

      Hi Unyime,

      It is a .htaccess mapping rule. The first part of the rule is the actual request url and it is mapped to the controller with adding the url parts as query parameters.

  • Julia Davis says:

    It was such a great article which was on PHP applications. PHP provides various caching mechanisms that can be implemented to optimize application performance. Here are a few common approaches:
    1.File-based Caching
    4.Opcode Caching
    This is some sort of information which I wanted to include in your article.

Leave a Reply

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

↑ Back to Top

Share this page