Simple cache in PHP without extra extensions

There are cases when you can’t use APC or Memcache or whatever cache extension you prefer on using in PHP. What follows is a simple way of implementing cache for an app. All you need is a writable folder somewhere on the server.

The implementation

The mechanism consists of three functions, operating with files on the server:

  1. The writeCache function takes your data, serializes it (if necessary) and writes it to a static file.
  2. The checkCache function reads the timestamp on the file that was written, compares it to a time frame you provided and returns false if the cache needs the be rewritten.
  3. The readCache function reads the contents of the cache file, unserializes it (if necessary) and returns it.
/*the base folder of the cache file(s) 
 * (assuming there are no open_basedir restrictions)
*/
$cacheFileBase = $_SERVER['DOCUMENT_ROOT'] . '/cache/';
 
/*the cache time in minutes - how long will the results be cached*/
$cacheTime = 10;
 
/*Function to check if a certain cache file needs to be updated*/
function checkCache( $identificator ) {
	global $cacheFileBase, $cacheTime;
 
	$file = $cacheFileBase . $identificator . '.txt';
 
	/*return false if the cache file doesn't exist*/
	if( !file_exists( $file ) ) {
		return false;
	}
 
	/*Return false if the file's cache time substracted 
	 * from the current time is larger than the cache time in seconds*/
	if( (time() - filemtime($file)) > $cacheTime * 60) {
		return false;
	}
 
	return true;
}
 
function writeCache( $identificator, $data ) {
	global $cacheFileBase;
 
	/*The full path to the cache file*/
	$file = $cacheFileBase . $identificator . '.txt';
 
	/*serialize the data if we're dealing with an array or an object*/
	if( is_array($data) || is_object($data) ) {
		$data = serialize($data);
	}
 
	if( file_put_contents($file, $data) ) {
		return true;
	}
 
	return false;
}
 
function readCache( $identificator ) {
	global $cacheFileBase;
 
	/*The full path to the cache file*/
	$file = $cacheFileBase . $identificator . '.txt';
 
	$data = file_get_contents($file);
 
	/*check to see if the data was 
	 * serialized so we know what to return
	 * http://stackoverflow.com/questions/2878218/check-if-string-is-serialized-in-php/2878254#2878254
	 * */
	$checkSerialization = @unserialize($data);
	if ( $checkSerialization !== false || $data === 'b:0;' ) {
	    $data = $checkSerialization;
	}
 
	return $data;
 
}

The usage

if( !checkCache('testing') ) {
	$test_data = array('test1', 'test2', 'test3');
 
	if( !writeCache('testing', $test_data) ) {
		//log the data if cache failed
	}
 
} else {
	$test_data = readCache('testing');
}
 
print_r($test_data);

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">