no more cache – force the reload based on the file date  [ 561 views ]

Goal: avoid cache in case of changed files

The cache is our friend in case of old files. With this code I can use the cache based on my file date.

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

the result is

<link href="css/main.css?1402529381" rel="stylesheet" type="text/css">

In a little bit friendly shape:

...
class no_cache{
  public static function css($fileName){
    echo('<link rel="stylesheet" type="text/css" href="'.self::get_file($fileName).'" media="screen"/>');
  }
  public static function js($fileName){
    echo('<script src="'.self::get_file($fileName).'"></script>');
  }
  public static function file($fileName){
    echo(self::get_file($fileName));
  }
  public static function get_file($fileName){
    return $fileName . '?' . filemtime($fileName);
  }
}
...
<?php 
  no_cache::css('css/main.css'); 
  no_cache::js('js/jquery-1.7.1.js');
  no_cache::js('js/main.js');
?>
... 
/* and the output is */
<link rel="stylesheet" type="text/css" href="css/main.css?1403178760" media="screen">
<script src="js/jquery-1.7.1.js?1368082485"></script>
<script src="js/main.js?1402517230"></script>
...

Shorter, smarter…

Call the no_cache class like

css: no_cache::css('css_file_path');
js: no_cache::js('js_file_path');
file: no_cache::file('file_path');
#sidebar a { color:#fff; } #sidebar ul ul li { color: #DEF585; } #sidebar h2 { color: #fff; } #sidebar ul p, #sidebar ul select { color: #BEDDBE; } #backfly { background: url(images/golfBallWallPaper.jpg) left bottom fixed repeat-x #65a51d; }