09.21.05

Access control and caching of files with PHP

Posted in web dev at 7:49 am by Clinton

...
if ($permission && file_exists(PATH.$filename)) {
   header('Content-Disposition: inline; filename='.$filename);
   header('Content-Type: image/jpeg');
   header('Content-Length: '.@filesize(PATH.$filename));
   @readfile($filename);
   exit;
} else {
  die('Who the heck are you? - or- What the heck are you asking for?');
}
...

Usually, if i really wanted to make sure that people didn’t cache the content I’d include some extra headers like
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
and I thought this was good. However, recently I used the same technique for a photo-gallery, and noticed that the performance was not good - images were not being cached (exactly what i’d asked for), and I really should have another think about this.

I went over to http://php.net/header but most of the notes people have left are about making sure things are not cached - I now wanted to allow caching for a limited time (say 10 mins).

Anyway, one of the user contributed comments lead me to the web-caching.com site, and they have good info on supporting the use of caching by sending the right headers. In particular I landed on their implementation notes and so I replaced my old cached control header with:

// allow cache for 600 seconds = 10 mins
header('Cache-Control: max-age=600');

and this works as advertised (afaik with the browsers i’ve tested).

Overall, i’ll be thinking about cache headers a little more carefully in future, because caching is not something to be avoided entirely, but used wisely, and makes the net a better place.
$0.05

Leave a Comment