PHP最后修改远程文件的时间

时间:2011-10-08 07:40:41

标签: php curl filetime

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

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

提前致谢

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

基于此解决方案
PHP: 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;
}

答案 2 :(得分:0)

我打算试一试并说你要连接的服务器可能是一个IIS网络服务器。

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

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