【发布时间】:2012-09-20 02:58:30
【问题描述】:
我如何知道文件是否在使用 CURL 打开流之前被修改过 (然后我可以用 file-get-contents 打开它)
谢谢
【问题讨论】:
-
如果您已经有该文件的副本,您可以使用 rsync。
-
太复杂了!还是谢谢
标签: php curl file-get-contents
我如何知道文件是否在使用 CURL 打开流之前被修改过 (然后我可以用 file-get-contents 打开它)
谢谢
【问题讨论】:
标签: php curl file-get-contents
检查CURLINFO_FILETIME:
$ch = curl_init('http://www.mysite.com/index.php');
curl_setopt($ch, CURLOPT_FILETIME, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_NOBODY, true);
$exec = curl_exec($ch);
$fileTime = curl_getinfo($ch, CURLINFO_FILETIME);
if ($fileTime > -1) {
echo date("Y-m-d H:i", $fileTime);
}
【讨论】:
curl_setopt($ch, CURLOPT_HEADER, 1); 并在其他网站上为Last-Modified 阅读$exec 来完成。
尝试先发送 HEAD 请求以获取目标 url 的 last-modified 标头,以比较您的缓存版本。您也可以尝试在使用 GET 请求创建缓存版本时使用 If-Modified-Since 标头,以便对方也可以使用 302 Not Modified 回复您。
使用 curl 发送 HEAD 请求如下所示:
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_NOBODY, true);
curl_setopt($curl, CURLOPT_HEADER, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTP_VERSION , CURL_HTTP_VERSION_1_1);
$content = curl_exec($curl);
curl_close($curl)
$content 现在将包含返回的 HTTP 标头,作为一个长字符串,您可以在其中查找 last-modified:,如下所示:
if (preg_match('/last-modified:\s?(?<date>.+)\n/i', $content, $m)) {
// the last-modified header is found
if (filemtime('your-cached-version') >= strtotime($m['date'])) {
// your cached version is newer or same age than the remote content, no re-fetch required
}
}
您也应该以相同的方式处理expires 标头(从标头字符串中提取值,检查该值是否在未来)
【讨论】: