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 |
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.
Do you need help with a project? or have a new project in mind that you need help with?
Contact Me