How to create a simple and efficient PHP cache | Techbirds

Posted on: May 15, 2014 /

Categories: PHP / Author Name: Rahul

When working on php websites made from scratch and without a framework, speed can often be an issue. Caching is extremely useful in order to speed up PHP webpages. In this article, I’ll show you a super easy and efficient way to dynamically cache php pages that need to be faster.

Step one: Create the top-cache.php file

We need to create two files. Here’s the first one: Create a new file named top-cache.php and paste the code below in it.


















So, what this code does? The first 5 lines create the cached file name according to the current php file. So, if you’re using a file named list.php, the cached file will be named cached-list.html.

Line 6 creates a $cachetime variable which determines the life of the cache.

Lines 9 to 13 are a conditional statement which look for a file named $cachefile. If the file is found, a comment is inserted (line 10) and the $cachefile file is included. Then, the exit statement stops the execution of the script and the file is sent to the client brother. Which means that if a static file is found, no php code is interpreted by the server.

Line 14 creates a buffer, if the $cachefile file isn’t found. That’s all for the top-cache.php file.

Step two: Create the bottom-cache.php file

Now, create a second php file, named bottom-cache.php and paste the code below in it.

If a file named $cachefile isn’t found on your server, this code is executed and create the file, so next time the page will be called, the $cachefile static file will be served to the client browser instead of executing the whole PHP file.

Step three: Include cache files on your page

Now that you have created the two necessary files, you simply have to include them on the php page you wish to cache. As you probably guessed, the top-cache.php file must be included in the beginning of your php page and the bottom-cache.php at the end, as shown below:

Now if you test the cache on a slow page, you’ll be amazed by how faster the page is. This easy cache is best solution when working on “from scratch” PHP websites.

584 total views, 2 views today

Share this Onfacebook-5847637twitter-4527824linkedin-2222558google-7228941