HomeAbout MeResumeKnowledgeProgrammingPHPCaching

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:
  • Check if cache file exists
  • Check if cache file has expired
    • Show Cache if valid
    • Start output buffer to capture cache if not valid
  • Write output buffer to a file on the local server
I have provided a live sample of caching on the rss page. Whenever I grab remote content I am careful to never retrieve more then is necessary. On the RSS page for example, I am reading in news from Yahoo and Google. Rather then request the news ever single time the page is loaded, I request it once, cache the results, and then display them each time the page is loaded for a certain time increment. Below is a quick sample of the php used to perform the above:
################
# 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 #
###############