blog
Image Caching With PHP

While working on my next project, I am looking for the best possible techniques to make it fastest possible (both client and server). My app requests a lot of images here and there, it may count up to hundreds or thousands requests in a while. I can not hold all of those wthin flash player cache because some of them may change, and I also want shortest possible respond times and client-server traffic reduction as well as server side computing reduction. Thats where browser caching comes into the scene. I have experimented a bit with all possible http headers to understed each browser specifics and I came with a solution.
// $this->time() - returns filemtime() for the file
// $this->filename() - returns full path to the file
$etag=md5($this->time().$this->filename());
$time=gmdate('r', $this->time());
header('Last-Modified: '.$time);
header("Cache-Control: must-revalidate");
header('Expires: '.$time);
header("Etag: ".$etag);
if(isset($_SERVER['HTTP_IF_MODIFIED_SINCE'])
|| isset($_SERVER['HTTP_IF_NONE_MATCH'])){
if($_SERVER['HTTP_IF_MODIFIED_SINCE'] == $time
|| str_replace('"', '', stripslashes($_SERVER['HTTP_IF_NONE_MATCH'])) == $etag) {
header('HTTP/1.1 304 Not Modified');
exit();
}
}
header("Content-Length: ".filesize($this->filename()));
header("Content-type: image/png");
readfile($this->filename());This is how it works:
flash app requests a new image (thorough browser) from php server, minimum requests headers added with browser while it is a new image
php server responds with important cache and Etag headers info and image bytes (content)
browser caches response headers, flash player handles response
Repeated request:
when flash player requests the same image again, browser adds Etag and date into request headers (while it caches the last response)
php server catches request headers and see browser cached info in $_SERVER vars
while Etag matches, it responds with 304 Not Modifed header and no content pushed (traffic is saved, server computing reduced)
browser push its cached content into flash player (faster response)
Now someone changes the image on php server:
flash player requests the image, browser adds headers
php server generates new Etag for the image and compares it with browser added request headers
those does not match so the new image content is pushed with response
Nice thing is, there are no random parameters required with your requests, while all requets are sent to the server and handled appropriately, so your content is always fresh. This script is tested with IE and Chrome (works as expected). I was not able to make my proxy watcher communicate with opera and my firefox settings are set to no-cache at all.