Force Refresh on New Cached Files
Read laterJust refresh your browser, of clear your cache.
I’ve heard these words at work so much that it got me thinking. If we’re having to tell clients to refresh, how are their views going to know? What if there was a way to force a new download of a file that’s cached locally in the users browser?
Well, I’ve had this idea for a while but never thought to write some code and implement it. PHP is the weapon.
The code & how it works
function timedCache($theTimedCacheFile) {
$theTimedCacheFileServerPath = $_SERVER["DOCUMENT_ROOT"] .''. $theTimedCacheFile;
echo $theTimedCacheFile . '?' . date("H:i:s--d-m-Y", filemtime($theTimedCacheFileServerPath));
}
It works by getting the date for file was last edited, that’s the filemtime function. It adds a more readable formatted time stamp onto the URL, the browser sees this, if the file with that time is not in the cache, it’ll download it.
The URL passed is relative to the root folder, this is so the script can add the document root (the hidden file path from the server) to the path yu specify. The filemtime works with absolute paths, so this is needed.
What’s returned is a absolute URL from the root folder. Writing the following;
<link rel="stylesheet/less" href="<?php timedCache('/wp-content/themes/CodeByMonkey/style.less'); ?>" />
Returns this;
<link rel="stylesheet/less" href="/wp-content/themes/CodeByMonkey/style.less?14:23:40--15-08-2010" />
Suggestions?
I’ll be using this code in projects at work, so I’m more than happy for suggestions on how to make this better.
