7

我想获取远程文件的最后修改时间。我正在使用我在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);

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

提前致谢

4

3 回答 3

4

鉴于我们在 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
于 2011-10-10T07:22:52.577 回答
1

基于此解决方案
远程文件大小无需下载文件

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;
}
于 2013-09-17T14:43:50.327 回答
0

I'm going to take a punt and say that the server you're connecting to might be an IIS web server.

In my case, I've found that the IIS 7 server I'm connecting to does NOT return a Last-Modified date when I issue a HEAD request via Curl using PHP (but it does return the Last-Modified when doing a usual GET request).

If you are in control over the server you're connecting to, see if you can get the web server to correctly issue the Last-Modified date. Otherwise don't use CURLOPT_NOBODY.

于 2012-05-11T06:59:04.553 回答