Cache Busting CSS & JS files with PHP
If you’re building a PHP site and want the browser to cache your CSS and JS files, all you need to do is get the last updated time of the file.
Because the file will only ever change when it’s updated, so will the query string. This is a very simple yet incredibly effective way of of leveraging browser caching.
In the below function we do a few things:
- Check the
$file_url
parameter has been passed. - See if that file does indeed exist by using PHP’s
file_exists()
function. - If it does, grab the lastest updated time of that file by using PHP’s
filemtime()
function.
<?php
function get_that_filetime($file_url = false) {
if($file_url && file_exists($file_url)) {
return filemtime($file_url);
}
}
?>
Then all you need to do is add the absolute file path of your CSS file (or JS file). The function will spit out some numbers (a unix timestamp) you can use as a query string.
<!-- Function in use -->
<link rel='stylesheet' href='style.css?ver=<?php echo get_that_filetime($_SERVER['DOCUMENT_ROOT'] . '/style.css'); ?>' type='text/css' media='all' />
<!-- Output -->
<link rel='stylesheet' href='style.css?ver=1530101131' type='text/css' media='all' />
Comments are closed for this post.