Clear Cache of Modified Files using PHP

Most large websites nowadays do a lot of updates to their JS and CSS files to give their customers a better browsing experience. The problem that most Web Developers face is the new codes are not pushed to the users, instead they are served the old cached version of the file.

Most of the answers when you Google this up is to simply add a time stamp to the end of your file URL. Sure! that works but your user’s browser will always have to re-download the file every time they load a new page in your website – this is not very efficient especially when you are working on large scaled websites. So what if we just change the time stamp ONLY when the file was modified?

Here is how you can do it:

1
2
3
4
5
6
7
function check_if_modified( $file_location ) {
    if( file_exists( $file_location ) ) {
        return filemtime( $file_location );
    } else {
        return false;
    }
}

The function above simply returns the time the file was last modified, this would mean that if the file was never modofied – the time stamp will never change.

Usage

1
2
3
4
5
6
7
8
9
10
<!DOCTYPE html>
<html>
    <head>
        <script src="app.js?<?php echo check_if_modified('/app.js'); ?>"></script>
    </head>
    <body>
        <h1>Carl Fontanos</h1>
        <p>Test!</p>
    </body>
</html>

NOTE: If you are running on a framework or platform like WordPress, the parameter must be the PATH to your file, as the functions that checks the existence and modification time of the file requires a valid path.

1
<script src="app.js?<?php echo check_if_modified( PATH_TO_FILE . '/app.js'); ?>"></script>