1

I am wondering how cache systems like doctrine-cache or zend-cache, set an expiry for cache files if those files are not in /tmp folder. How is possible to set an expiry for cache files? If I want to use my own cache file system with php rather than using doctrine or zend, how can I set an expiry for it if I don't want to place it in /tmp folder?

user4271704
  • 723
  • 1
  • 12
  • 37

2 Answers2

2

The cache is pretty simple. Let's say you have directory cache. You set expiration time for files which are there under variable $expire

So the algorithm is

$file = "cache/cached.jpg";
$expire = 60 * 3600;

if (filectime($file) > time() + $expire)
{
   // reload file and invalidate cache
} else if (file_exists($file){
   // get from cache
} else {
  // get file and save it to cache then return  
}

but it's better to use caches that are there like http cache etc with expire header, varnish etc.

Robert
  • 19,800
  • 5
  • 55
  • 85
  • Actually I want to use it for a .dat ir .txt file, not a page, so is it still possible to use http cache as you said? In your sample cache expires after 60 hours? For .txt file still better to use filectime rather than filemtime? @Robert – user4271704 Sep 13 '16 at 11:40
  • yes it is possible to do by webserver for example in apache http://httpd.apache.org/docs/current/mod/mod_expires.html – Robert Sep 13 '16 at 15:10
1

I would recommend using cache service as Memcached. There is a third parameter to a set function, which means number of seconds after which the value will expire.

Wax Cage
  • 788
  • 2
  • 8
  • 24
  • I know about in memory cache systems. But here my question is about file cache. Anyway, I still vote up for you. – user4271704 Sep 13 '16 at 11:42
  • Oh. Then I think you must program the logic of expiring by yourself. Look at this answer: http://stackoverflow.com/questions/5262857/5-minute-file-cache-in-php – Wax Cage Sep 13 '16 at 12:26
  • As suggested in that link how to lock with rename()? It locks sutomatically or which parameter should I pass to lock? @Wax Cage – user4271704 Sep 13 '16 at 13:05
  • I dont understand file locking too much, but this answer seem to explain it a lot: http://stackoverflow.com/questions/4899737/should-lock-ex-on-both-read-write-be-atomic/4899822#4899822 – Wax Cage Sep 13 '16 at 13:09
  • Maybe I would personally recommend, if you are building a php component like for your framework or so, to not let any other processes to modify your cached files and just script your own application locking (where each time you want to use a cache file, you must check the lock). – Wax Cage Sep 13 '16 at 13:15