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:

    function get_that_filetime($file_url = false) {
        if (!file_exists($file_url)) {
            return '';

        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.

// Example
<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' />

Inspirational Newsletter

Join the newsletter to get the best articles, tutorials and exclusive freebies every two weeks.

No spam. You can unsubscribe at any time.