PHP File-System Cache

I’m just sharing a couple of functions I created a while back to cache some resource-intensive processed dada for quick and easy access. This is pretty ideal for large amounts of data and it’s very simple to set up. The beauty of this is that you can store just about any data type – it doesn’t have to be a string.

Just setup the cache directory to have proper read/write permissions (preferably in a non-accessible from web directory). Then use the two functions.

Example usage:

// The 2nd argument, $hours is how long to retain data before getting new
$contents = get_cache('TEST_KEY', 24);
if ($contents === false) {
	// This is where you'd get data from an API, DB or whatever
	$contents = 'Just some example contents';
	set_cache('TEST_KEY', $contents);
echo $contents;


define('CACHE_DIR', 'cache/'); // Include trailing slash

function get_cache($key, $hours) {
	$file = CACHE_DIR . md5($key) . '.cache';
	if (!file_exists($file) || filemtime($file) < time() - $hours * 3600)
		return false;
	return unserialize(file_get_contents($file));

function set_cache($key, $value) {
	$file = CACHE_DIR . md5($key) . '.cache';
	file_put_contents($file, serialize($value));

HTML Optimizer & Compressor

Quite often I create an HTML file, possibly generated dynamically, that sees a ton of exposure. To save loading time and bandwidth, I optimize/compress the static files (HTML, CSS, and Javascript). I’ve found very good tools for packing Javascript and CSS, Dean Edwards’ packer and CSS Drive’s compressor respectively, but haven’t found a great tool for optimizing HTML. The following tool is something I whipped up in which simply removes whitespace and comments from HTML and tells you how much disk space you are saving. Careful, it could possibly mess up your javascript or anything else whitespace sensitive (pre tags, etc), but should do the job for most tasks. Admittedly this might be more convenient as a web application, and it wouldn’t take much, but I created it personally for my uses so I can use it offline as well.

Download: (7.92KB)