Enable better caching on your website using PHP

by Richard Bradshaw

Just a quick snippet to help you tell useragents accessing your site that the content hasn’t changed.

function caching_headers ($file, $timestamp) {
	$gmt_mtime = gmdate('r', $timestamp);
	header('ETag: "'.md5($timestamp.$file).'"');
 
	if(isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) || isset($_SERVER['HTTP_IF_NONE_MATCH'])) {
		if ($_SERVER['HTTP_IF_MODIFIED_SINCE'] == $gmt_mtime || str_replace('"', '', stripslashes($_SERVER['HTTP_IF_NONE_MATCH'])) == md5($timestamp.$file)) {
			header('HTTP/1.1 304 Not Modified');
			exit();
		}
	}
 
	header('Last-Modified: '.$gmt_mtime);
	header('Cache-Control: public');
	return 1;
}

Then call this in the top of your code like this:

caching_headers ($_SERVER['SCRIPT_FILENAME'], filemtime($_SERVER['SCRIPT_FILENAME']));

This sets an Etag based on the filename and modification date, and just returns a 304 header without any content if the browser already as the content.

You can also supply a different unix timestamp as the second argument allowing the timestamp to come from a database if applicable.

Hope this comes in useful!

Related Posts