Caching Made Easy… Lower Server Load on PHP/MySQL WebSites

Caching Made Easy…  Lower Server Load on PHP/MySQL WebSites

I used to always compile the pages every morning on my site so that they were static, however I wanted a more automatic solution. Below I will show you how to Cache any PHP webpage automatically.

First you will need to download the php library below and upload it to your webserver.

http://pear.php.net/package/Cache_Lite

Next let’s create the php script that will control the cache.

Place Section 1 in the very top of your php page.

<?php
require_once('YOUR-CACHE-DIRECTORY/cache/Lite.php');
 
$pageid = "CREATE-A-UNIQUE-PAGE-ID-OR-NAME";
 
$options = array(
'cacheDir' = 'YOUR-CACHE-DIRECTORY/cache/',
'lifeTime' = 28800
);
 
$Cache_Lite = new Cache_Lite($options);
 
if($data = $Cache_Lite->get($pageid))
{
	echo $data;
 
} else { // No valid cache found (you have to make the page)
 
	ob_start();
?>

#######################
This is where your php file is loaded and content is echoed.
#######################

Now place the code below at the very end of your php file.

<?php
 
	$final_data = ob_get_contents();
 
	ob_end_flush();
 
	$Cache_Lite->save($final_data); // this will save your output
} // close else statement
?>

Once completed, the first load should create your cached file. The second time you refresh the page it should show you the cached file.

As always, please leave comments below.

About the Author