Search code examples
phpcachingfilemtime

PHP filemtime cache different day issue


I want to cache file for 5 minutes but filemtime with different day always return false, here the code

<?php
error_reporting(E_ALL);
date_default_timezone_set("Asia/Jakarta");
$cache_file = 'myfile';
$cachetime = time() - 5*60;

if(filemtime($cache_file) >  $cachetime ) {
  echo "Cache Expired";
}
else{
  echo "File Mod: ".filemtime($cache_file)." >>> ".date("F d Y H:i:s", filemtime($cache_file))."<br>";
  echo "Time Now: ".$cachetime." >>> ".date("F d Y H:i:s", $cachetime)."<br>";
}
?>

and output

File Mod: 1431696549 >>> May 15 2015 20:29:09
Time Now: 1431716474 >>> May 16 2015 02:01:14

thanks for your help.


Solution

  • Looks like your logic is off. You want to create a timestamp of the given modification time PLUS the TTL, and compare this to the current time.

    $cachetime = filemtime($cache_file) + 5*60;
    
    if($cachetime > time()) {
      echo "Cache Expired";
    }