|
Home ⇒ About Me ⇒ Resume ⇒ Knowledge ⇒ Programming ⇒ PHP ⇒ Caching ⇒ Caching
Reducing server load using caching Caching: "Web documents retrieved may be stored (cached) for a time so that they can be conveniently accessed if further requests are made for them. The issue of whether the most up-to-date copy of the file is retrieved is handled by the caching program which initially makes a brief check and compares the date of the file at its original location with that of the copy in the cache. If the date of the cached file is the same as the original, then the cached copy is used." Because the web has become so dynamic with entire websites being driven by a database, or even by remote content, caching has become a major importance to reduce the load on local and remote resources. I have a few general scripts that I use to Cache both entire pages, and individual sections within a page. The function works as follows:
################
# START BEGIN CACHE #
################
# CACHE SETTINGS
$cachedir = '/path/to/cache/dir/';
$cachetime = 86400;
$cachename = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
$cachefile = $cachedir . md5($cachename) . '.cache';
# CHECK FOR EXISTING
$cachefile_created = (@file_exists($cachefile)) ? @filemtime($cachefile) : 0;
@clearstatcache();
# SHOW IF CACHE FILE VALID
if (time() - $cachetime < $cachefile_created) {
$cache_file = file_get_contents($cachefile);
} else {
# ELSE START OUTPUT BUFFER
ob_start();
}
################
# FINISH BEGIN CACHE #
################
# EX. PERFORM DB INTENSIVE REPORTING HERE - THEN CACHE TO FLATFILE TO SPEED UP LOAD TIME
###############
# START END CACHE #
###############
# OPEN CACHE TO FILE
$fp = @fopen($cachefile, 'w');
# WRITE TO CACHE FILE
@fwrite($fp, ob_get_contents());
@fclose($fp);
ob_end_flush();
###############
# FINISH END CACHE #
###############
|