PHP cURL标头请求在某些服务器上返回400

时间:2013-05-11 13:09:36

标签: php http curl monitoring

我正在尝试使用cURL测试来自少数客户端网站的服务器响应,仅检索标头,包含在microtime调用中以计算完整执行时间(用于服务器往返),以及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);

代码包含在Object中,所有相关变量都被正确传递,修剪和清理。因为我需要调用服务器IP,所以它将作为CURLOPT_URL传递,并在Header中传递URL。我试过设置引用者,但这没有帮助。

谢谢,

1 个答案:

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