Browser Cacheable PHP Scripts

Let’s say you have a script that outputs an image and you want the browser to cache it, just as it does static images. You can accomplish this by supplying some headers with the image, and then checking for certain headers when the server receives subsequent requests for the same image.

You can do this a number of different ways, but the method I’m demonstrating here is based on the modification time of the image. The process works essentially like this:

  1. The browser sends a request to the server for the image.
  2. The server responds with the image and some headers, including the image’s modification time.
  3. The next time the browser sends a request for the image, it sends along the modification time provided in the last step.
  4. The server checks if the modification time the browser sent with the request matches the current version of the image.
    • If the image the browser has is “fresh”, the script responds with a 304 Not Modified header to let the browser know to use the file it already has.
    • If the image is out of date, the script sends a new image, along with the new modification date.

Sample Code

// $image_blob is the contents of a JPEG.
// $image_date is the timestamp the image was last changed.

// If the browser supplied an If-Modified-Since header that is not later than
// the modified date, issue a 304 header.
if (
	isset($_SERVER['HTTP_IF_MODIFIED_SINCE'])
		&&
	$image_date <= strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE'])
)
{
	header('HTTP/1.1 304 Not Modified');
	header('Content-Length: 0');
	exit;
}

// Otherwise, send the image and appropriate headers.
else
{
	header('Content-Type: image/jpeg');
	header('Content-Length: ' . strlen($image_blob));
	header('Last-Modified: ' . gmdate('D, d M Y H:i:s', $image_date) . ' GMT');
	header('Pragma: public');
	print $image_blob;
	exit;
}

That’s about it. Happy cacheing!

Share and Enjoy:
  • Twitter
  • Facebook
  • Reddit