How to create your own PHP caching system? A simple example
Caching really increases your web site performance on highly loaded environments. For instance, creating a page of this site is usually takes about 100ms including all MySQL queries. It means that your CPU and some of your RAM is dedicated for creating your dynamic PHP page.
If there are more than 50 people accessing your pages simultaneously, your CPU can overflow and cannot complete some of the requests. Thus, you will experience many page drops.
In order to escape from this challange, just use PHP caches. Cache means that creating temporary HTML files from your dynamic PHP pages to handle the requests faster. Here is my PHP code that should be included as
require_once('cache.php');
in the beginning of each PHP file that have same results when they are requested. Using caching technology, your web site can easily overcome CPU and RAM overflow problems. Here is my "cache.php" file.
< ?php
classCache
{
public $start_time;
public $cache_file;
public $to_create;
function __construct()
{
$this->to_create = TRUE;
$this->Start();
}
function Start()
{
$this->start_time = microtime();
$cache_time = 60; // use cache files for 60 seconds
$str = $_SERVER['REQUEST_URI'];
foreach ($_GET as $k => $v)
$str .= $k . $v;
foreach ($_POST as $k => $v)
$str .= $k . $v;
$this->cache_file = $_SERVER['DOCUMENT_ROOT'] . "/cache/" . md5($str) . ".html";
if (file_exists($this->cache_file) && (time() - $cache_time < filemtime($this->cache_file)))
{
include($this->cache_file);
$end_time = microtime();
echo "< !-- " . $end_time - $this->start_time . " ms -->";
$this->to_create = FALSE;
exit;
}
ob_start();
}
function End()
{
$fp = fopen($this->cache_file, 'w');
fwrite($fp, ob_get_contents());
fclose($fp);
ob_end_flush();
$end_time = microtime();
echo "< !-- " . $end_time - $this->start_time . " ms -->";
}
function __destruct()
{
if ($this->to_create)
$this->End();
}
}
$cache = new Cache();
?>
Just try it to increase abilities of your web server. Note that, cache files are created into ‘cache’ directory. Please create a new directory to collect your cache files.
Last Note:
Use professional caching tools for better performance!