How to Implement Caching in PHP Application

cache

Caching is a mechanism to save a HTML version of your dynamic pages and server these HTML pages instead of dynamic pages. In this way, your server will not have to process PHP script or run various database query. It will make your website faster. your website will also use less server resources. If you are on shared hosting, it will help you a lot in making your website faster.

PHP Cache

If you are using a CMS, implementing caching is easy. Most of the CMS comes with caching add-on or plugin. In WordPress there are few nice caching WordPress plugins available. But what if you have coded PHP script manually. In this case, you can add caching manually in your PHP application. Few days back while working on my gadgets project, I faced heavy resource usage problem. So, I tried adding caching in PHP manually and got success. After adding caching I was able to improve the load time and host more traffic on the shared hosting environment. But you should also have good hosting for better speed. See recommended Web Hosting providers.

Also Read: Reliable Web hosting with Bluehost

I also thought to share the same process with our readers. I am adding the basic process, not the same I added. You can change it to improve as per your requirement and expertise.

Note: This code is for server side caching. Cache pages will be stored in a cache folder. And you also need to give write permission to this caching folder.

<?php
$time_start = microtime(true);
$url = md5($_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"]);
$cachefile = 'cache/'.$url.'.cache'; // e.g. cache/index.php.cache
$cachetime = 3600; // time to cache in seconds

if(file_exists($cachefile) && time()-$cachetime <= filemtime($cachefile)){
$c = @file_get_contents($cachefile);
echo $c;
$time_end = microtime(true);
$time = $time_end - $time_start;

echo "<!-- cache page generated in: ".$time." -->";
exit;
}

ob_start();

////

/// Your code PHP goes here.

////

$c = ob_get_contents();

$time_end = microtime(true);
$time = $time_end - $time_start;
echo "<!-- non cache page in: ".$time." -->";
file_put_contents($cachefile, $c);

?>

I am using this code to cache pages in my gadgets.techlomedia.in website. It is working fine and saving thousands of SQL queries every hours. In this way, I can better utilize my web hosting server.

I recommend you to use this code to cache your PHP application pages. If you face any problem, you can ask me any time via the comments section below.

Tags: |

Deepanker Verma is the founder of Techlomedia. He is a tech blogger, developer and gadget freak.


Similar Articles

0 Comments

Leave a comment

Comment policy: We love comments and appreciate the time that readers spend to share ideas and give feedback. However, all comments are manually moderated and those deemed to be spam or solely promotional will be deleted.

2020 UseThisTip | Part of Techlomedia Internet Pvt Ltd Developed By Deepanker