Timeout for a cache file in php

2.5k Views Asked by At

In php, i create a cache file in order to stock complexe results variables. One variable, one cache file. Well done its work fine.

The problem lies in the term of the cache. For the moment i put into the file the timeout and the variable, but its not optimized because i must open the file to check the timeout.

I want to (if its possible) check the timeout to a file property (like date last modified with the function filemtime()). Can we add custom property to a file?

The other way is to add the timeout in the filename, not my favorite solution.

[Edit]

final class Cache_Var extends Cache {

  public static function put($key, $value, $timeout=0) {
    // different timeout by variable (if 0, infinite timeout)
  }

  public static function get($key) {
    // no timeout to get a var cache
    // return null if file not found, or if timeout expire
    // return var otherwise
  }
}
1

There are 1 best solutions below

2
On BEST ANSWER

filectime()can really help you

$validity = 60 * 60; // 3600s = 1 hour
if(filectime($filename) > time() - $validity) {
  // cache is valid
} else {
  // cache is invalid: recreate it
}

There are some caching fdrameworks around that use exactly this mechanism.

Edit: If you need different timeouts per cache item than use touch()to set modification time of cache files. You could even set modification time to a future value and directly compare filectime with current time.

final class Cache_Var extends Cache {

  public static function put($key, $value, $timeout=0) {
    // different timeout by variable (if 0, infinite timeout)
    // ...
    touch($filename, time() + $timeout);

    // For static files with unlimited lifetime I would simply store
    // them in a separate folder
  }
}