Stop Caching Old Files – A PHP Function

by keif on March 27, 2009

It’s weird that I swear David Walsh follows me around – everytime I have a conversation with someone about something, he writes an article about it – like preventing your css and javascript from being cached.

I had come to the same conclusion (from by conversation with Toby) that random querystrings being appended didn’t make much sense – that prevents caching, but why stop caching – unless the file gets updated?

I wrote a little php function that works with filemtime, albeit it requires the absolute path of the file.

[code lang=”php”]

function autoVer($url){
$path = pathinfo($url);
$ver = ‘.’.filemtime($_SERVER[‘DOCUMENT_ROOT’].$url);
echo $path[‘dirname’].’/’.$path[‘basename’].’?’.$ver;
}

[/code]

What this means, is when we call our files like so:

[code lang=”php”]

[/code]

So only when your file gets updated, does the query update, forcing the cache invalid!

It’s a simple function – and by no means perfect. Would you refactor it, or do you have a better way?

Comments on this entry are closed.

Previous post:

Next post: