I am a fresher to web development.
In my application I need to have caching so any one can explain me how to do caching of PHP pages in detail?
First make a folder called cache at the root of your site and make it writeable.
I have a file called caching_functions.php that looks like this:
<?
$test_server = $_SERVER['SERVER_NAME'] == "127.0.0.1" || $_SERVER['SERVER_NAME'] == "localhost" || substr($_SERVER['SERVER_NAME'],0,3) == "192";
$caching = !$test_server;
function start_caching($page) {
global $caching;
$hash = md5($page);
if ($caching) {
$cachefile = "cache/".$hash.".html";
if (file_exists($cachefile)) {
include($cachefile);
echo "<!-- Cached on ".gmdate('r', filemtime($cachefile))." to ".$hash." -->";
exit;
} else {
ob_start();
return $cachefile;
}
}
}
function end_caching($cachefile) {
global $caching;
if ($caching) {
$fp = fopen($cachefile, 'w');
// fwrite($fp, ob_get_contents());
fwrite($fp, preg_replace('!\s+!', ' ', str_replace(array("\n", "\t"),"",ob_get_contents())));
fclose($fp);
ob_end_flush();
}
}
function remove_cache() {
foreach (glob($_SERVER['DOCUMENT_ROOT']."/cache/*.*") as $filename) {
unlink($filename);
}
}
?>
I then put at the top of each page:
and at the bottom:
<? end_caching($cachefile); ?>
This makes the first request for a page get dumped to the cache folder. Subsequent visits use the cached version, and don't hit the database or do anything complex.
I'd make a page called clearcache.php and include the caching_functions and get it just to run remove_cache(). That will let you easily remove the cached files when needed.
This also only runs when not local, so make sure that you either change $caching to 1 if you want to test locally, or only test on a real server.
Caching in PHP can be mean storing the results of a particular function last time it was called in case that function is called multiples times in the same script (with the same parameters).
However I think the main and more powerful meaning is storing the complete output of a dynamically generated page, and serving this up when the page is requested again instead of actually running the full PHP script to regenerate that content.
For pages I want to cache, I have an AJAX command that writes the content into a database after the page is generated. It also adds an expiry time - say time() + 20 (expire in 20 seconds).
Then I add a condition at the top of the page to check for an unexpired cache for the page in the database. If found it returns that, otherwise it continues to re-generate the full page.
This article helped me get started:
http://simas.posterous.com/php-data-caching-techniques
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With