PHP中有5分钟的文件缓存 [英] 5-minute file cache in PHP

查看:203
本文介绍了PHP中有5分钟的文件缓存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常简单的问题:在PHP中下载文件的最佳方式是什么?只有当5分钟前下载了本地版本?



在我的实际情况下,我想从远程托管的csv文件获取数据,我目前使用的是

  $ file =的file_get_contents($网址); 

没有任何本地副本或缓存。最简单的方法是将其转换为缓存版本,最终结果不会更改($文件保持不变),但是如果不久前(例如5分钟)被提取,则使用本地副本? / p>

解决方案

使用本地缓存文件,只需检查文件的存在和修改时间,然后再使用它。例如,如果 $ cache_file 是本地缓存文件名:

  if (file_exists($ cache_file)&(filemtime($ cache_file)>(time() -  60 * 5))){
//缓存文件小于5分钟。
//不要打扰刷新,只需按原样使用该文件。
$ file = file_get_contents($ cache_file);
} else {
//我们的缓存过期,所以从我们的远程服务器
//加载数据,并将其保存在我们的缓存下一次。
$ file = file_get_contents($ url);
file_put_contents($ cache_file,$ file,LOCK_EX);
}

(未经验证,但根据我目前使用的代码) p>

通过这段代码,$ file最终将作为您需要的数据,如果是新鲜的,它将使用缓存,或者从远程服务器获取数据,如果没有,请刷新缓存。



编辑:自从写了上面的内容后,我更了解一些文件锁定。如果您担心这里的文件锁定,可能需要阅读此答案



如果您担心锁定和并发访问,我会说最干净的解决方案是将file_put_contents添加到临时文件,然后 rename() 它超过 $ cache_file ,它应该是一个原子操作,即 $ cache_file 将是旧的内容或全新的内容,从未写过。


I have a very simple question: what is the best way to download a file in PHP but only if a local version has been downloaded more than 5 minute ago?

In my actual case I would like to get data from a remotely hosted csv file, for which I currently use

$file = file_get_contents($url);

without any local copy or caching. What is the simplest way to convert this into a cached version, where the end result doesn't change ($file stays the same), but it uses a local copy if it’s been fetched not so long ago (say 5 minute)?

解决方案

Use a local cache file, and just check the existence and modification time on the file before you use it. For example, if $cache_file is a local cache filename:

if (file_exists($cache_file) && (filemtime($cache_file) > (time() - 60 * 5 ))) {
   // Cache file is less than five minutes old. 
   // Don't bother refreshing, just use the file as-is.
   $file = file_get_contents($cache_file);
} else {
   // Our cache is out-of-date, so load the data from our remote server,
   // and also save it over our cache for next time.
   $file = file_get_contents($url);
   file_put_contents($cache_file, $file, LOCK_EX);
}

(Untested, but based on code I use at the moment.)

Either way through this code, $file ends up as the data you need, and it'll either use the cache if it's fresh, or grab the data from the remote server and refresh the cache if not.

EDIT: I understand a bit more about file locking since I wrote the above. It might be worth having a read of this answer if you're concerned about the file locking here.

If you're concerned about locking and concurrent access, I'd say the cleanest solution would be to file_put_contents to a temporary file, then rename() it over $cache_file, which should be an atomic operation, i.e. the $cache_file will either be the old contents or the full new contents, never halfway written.

这篇关于PHP中有5分钟的文件缓存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆