【问题标题】:PHP cURL Header request returning 400 on some serversPHP cURL Header 请求在某些服务器上返回 400
【发布时间】:2013-05-11 13:09:36
【问题描述】:

我正在尝试使用 cURL 测试来自几个客户端网站的服务器响应,以仅检索标头,包裹在微时间调用中以计算完整执行时间(用于服务器往返)和 HTTP 状态代码,以便我自己和客户可以知道任何问题。

我需要通过服务器 IP 调用 cURL,并在那里定义主机,因为我希望 100% 确保消除 DNS 服务器停机时间 - 我正在使用另一个脚本来确保我的 DNS 副本是最新的,所以这不是一个问题。

我正在使用以下代码,该代码可在 90% 的服务器上运行,但少数人拒绝使用 400 和 404 代码,尽管可以在浏览器中访问。

    // Setup headers
    $header[] = "Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5";
    $header[] = "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7";
    $header[] = "Accept-Language: en-us,en;q=0.5";
    $header[] = "Cache-Control: max-age=0";
    $header[] = "Connection: keep-alive";
    $header[] = "Host: $this->url";
    $header[] = "Keep-Alive: 300";
    $header[] = "Pragma: "; // browsers keep this blank.

    $starttime = microtime(true);
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, "http://{$this->ip}/");
    curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
    curl_setopt($curl, CURLOPT_USERAGENT,"MyMonitor/UpCheck");
    // curl_setopt($curl, CURLOPT_REFERER, 'http://www.mysite.com/');
    curl_setopt($curl, CURLOPT_HTTPGET, true);
    curl_setopt($curl, CURLOPT_NOBODY, true);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, false);
    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, false);
    curl_setopt($curl, CURLOPT_TIMEOUT, $this->timeout); //timeout in seconds
    $this->header = curl_exec($curl);
    $this->statuscode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
    curl_close($curl);

代码封装在一个对象中,所有相关变量都被正确传递、修剪和清理。因为我需要调用服务器IP,所以这是作为CURLOPT_URL 传递的,URL 是在Header 中传递的。我试过设置referer,但这没有帮助。

谢谢,

【问题讨论】:

  • 是否可以在浏览器中访问它们使用 ip 而不是地址
  • 不直接,不 - 站点都在共享主机或 VPS 主机上,因此它需要地址来识别服务器内的站点。我怀疑这可能是客户端服务器配置的结果,但希望有办法解决。

标签: php http curl monitoring


【解决方案1】:

如果您只需要标题的第一行,那么使用 curl 就大材小用了。使用套接字函数,您可以在收到第一行状态码后立即关闭连接:

$conn = fsockopen($this->ip, 80);
$nl = "\r\n";
fwrite($conn, 'GET / HTTP/1.1'.$nl);
foreach($header as $h) {
    fwrite($conn, $h.$nl);
}
fwrite($conn, $nl);

$statusLine = fgets($conn);
fclose($conn);

$status = substr($statusLine, 9, 3);

【讨论】:

  • 啊,速度非常快,谢谢!我还不能投票,但当我得到更多分数时,我一定会 +1 这个答案。这应该可以节省很多开销,非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-20
  • 2022-12-16
  • 1970-01-01
  • 2018-04-07
  • 1970-01-01
  • 2019-03-31
相关资源
最近更新 更多