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

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

问题描述

我有一个非常简单的问题:什么是最好的方式下载一个文件在PHP,但只有当本地版本已经下载超过5分钟前​​?



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

的数据

  $ file = file_get_contents($ url);没有任何本地副本或缓存的

最简单的方法是将其转换为缓存版本,其中最终结果不会改变($ file保持不变),但是如果不是很久以前(例如5分钟),它使用本地副本? / p>

解决方案

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

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

(未测试,但基于我目前使用的代码。)

无论如何,通过这个代码,$ 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天全站免登陆