我想获取远程文件的最后修改时间。我正在使用我在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请求的消息,或者可能涉及到困难的代理。
当我调试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
基于此解决方案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;
}
我要打个and,说您要连接的服务器可能是IIS Web服务器。
就我而言,我发现连接到的IIS 7服务器在使用PHP通过Curl发出HEAD请求时没有返回Last-Modified日期(但是当执行通常的GET请求)。
如果您控制着所连接的服务器,请查看是否可以使Web服务器正确发布上次修改日期。否则,请勿使用CURLOPT_NOBODY。