【问题标题】:CURL get file only if had been modifiedCURL 仅在已修改时获取文件
【发布时间】:2012-09-20 02:58:30
【问题描述】:

我如何知道文件是否在使用 CURL 打开流之前被修改过 (然后我可以用 file-get-contents 打开它)

谢谢

【问题讨论】:

  • 如果您已经有该文件的副本,您可以使用 rsync。
  • 太复杂了!还是谢谢

标签: php curl file-get-contents


【解决方案1】:

检查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);
} 

【讨论】:

  • 它工作得很好,但我现在有另一个问题!我正在尝试获取文件的更改日期,例如:streaming204.radionomy.com:80/LoveHitsRadio 我得到的这个日期是 1970-01-01 00:59:59 当然是错误的!我该怎么做?
  • 我认为你不能这样做,因为那是流媒体收音机。很高兴它对您有所帮助。
  • 如果服务器不想返回 FILETIME,你就无能为力了。在您的情况下,它返回 501 错误。但可以使用curl_setopt($ch, CURLOPT_HEADER, 1); 并在其他网站上为Last-Modified 阅读$exec 来完成。
  • 对不起,我不明白在这种情况下我能不能做到!我试图设置 curl_setopt($ch, CURLOPT_HEADER, 1);但 $exec 告诉我:HTTP/1.0 501 Not Implemented
  • 是的,服务器不想返回任何东西(要么响应不正确,要么需要升级)。
【解决方案2】:

尝试先发送 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 标头(从标头字符串中提取值,检查该值是否在未来)

【讨论】:

  • 我是 curl 新手,所以我不明白!
猜你喜欢
  • 2018-12-22
  • 1970-01-01
  • 1970-01-01
  • 2017-01-16
  • 2016-03-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多