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:

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.


<!DOCTYPE html>
        <script src="app.js?<?php echo check_if_modified('/app.js'); ?>"></script>
        <h1>Carl Fontanos</h1>

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.

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

Related Post

Latest Post

Recent Posts Widget

Make sure to never miss a thing...

Get the latest news from the creative industry along with other creative goodies, conveniently delivered to social media.