【问题标题】:PHP last modification time of the remote filePHP远程文件的最后修改时间
【发布时间】:2011-12-03 11:21:40
【问题描述】:

我想获取远程文件的最后修改时间。我正在使用我在 stackoverflow 上找到的这段代码

$curl = curl_init();

    curl_setopt($curl, CURLOPT_URL,$url);
    //don't fetch the actual page, you only want headers
    curl_setopt($curl, CURLOPT_NOBODY, true);
    curl_setopt($curl, CURLOPT_HEADER, true);
    //stop it from outputting stuff to stdout
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

    // attempt to retrieve the modification date
    curl_setopt($curl, CURLOPT_FILETIME, true);

    $result = curl_exec($curl);
    echo $result;
    $info = curl_getinfo($curl);
    print_r($info);
    if ($info['filetime'] != -1) { //otherwise unknown
        echo date("Y-m-d H:i:s", $info['filetime']); //etc
    }  

这段代码的问题我总是得到 filetime = -1。但是当我删除

curl_setopt($curl, CURLOPT_NOBODY, true);

然后我得到正确的修改时间。

是否有可能获得上次修改时间但使用

curl_setopt($curl, CURLOPT_NOBODY, true);

包含在脚本中。 我只需要页面的标题,而不是正文。

提前致谢

【问题讨论】:

  • 您是否得到任何实际的标题信息?某些服务器可能(错误)配置为不响应 HEAD 请求。
  • 是的,我正在获取标题信息,但仅当代码中没有 curl_setopt($curl, CURLOPT_NOBODY, true); 时。

标签: php curl filetime


【解决方案1】:

鉴于我们在 Q/A 讨论中添加的信息,听起来您确实没有得到回应。可能是服务器配置了某种出于某种原因有意或无意地阻止 HEAD 请求的类型,或者可能涉及到困难的代理。

当我调试 PHP cURL 的东西时,我经常发现使用 *nix 框(我的 mac,或 ssh 到服务器)并从命令行运行请求很有用,所以我可以不用担心看到结果关于 PHP 是否在做正确的事情,直到我让 cURL 部分工作。例如:

$ curl --head stackoverflow.com

HTTP/1.1 200 OK
Cache-Control: public, max-age=49
Content-Length: 190214
Content-Type: text/html; charset=utf-8
Expires: Mon, 10 Oct 2011 07:22:07 GMT
Last-Modified: Mon, 10 Oct 2011 07:21:07 GMT
Vary: *
Date: Mon, 10 Oct 2011 07:21:17 GMT

【讨论】:

  • 我不知道在 Windows 7 上是不是这样
  • 对不起,我对 Win 系统一无所知。
【解决方案2】:

基于此解决方案
Remote file size without downloading file

function retrieve_remote_file_time($url) {
    $ch = curl_init($url);

     curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
     curl_setopt($ch, CURLOPT_HEADER, TRUE);
     curl_setopt($ch, CURLOPT_NOBODY, TRUE);
     curl_setopt($ch, CURLOPT_FILETIME, TRUE);

     $data = curl_exec($ch);
     $filetime = curl_getinfo($ch, CURLINFO_FILETIME);

     curl_close($ch);

     return $filetime;
}

【讨论】:

  • 如果我从 ftp 目录获取文件,此解决方案在我的情况下不起作用。
【解决方案3】:

我要赌一把,说您要连接的服务器可能是 IIS Web 服务器。

在我的情况下,我发现当我使用 PHP 通过 Curl 发出 HEAD 请求时,我连接到的 IIS 7 服务器不返回 Last-Modified 日期(但它在执行时确实返回 Last-Modified一个普通的 GET 请求)。

如果您可以控制要连接的服务器,请查看您是否可以让 Web 服务器正确发出 Last-Modified 日期。否则不要使用 CURLOPT_NOBODY。

【讨论】:

    猜你喜欢
    • 2011-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-06
    • 1970-01-01
    相关资源
    最近更新 更多