Quick php fix to CSS and Javascript browser cache

I am going to post very handy tip for javascript and css files caching. Browsers automatically cache the css and JS files and when you make change to CSS and JS some times change does not appears.

To prevent this use following

<?php
echo '<link rel="stylesheet" type="text/css" href="style.css?' . filemtime('style.css') . '" />';
?>

And For JS

<?php
echo '<script type="application/javascript"="main.js?' . filemtime('
main.js') . '" />';
?>

The PHP function filemtime returns last modified date of file, so every time you make change in css / JS files the filemtime will return different value and CSS / JS Url will change and browser will refresh CSS / JS file.

😉

Advertisements