2013-05-11 13:09
浏览 80

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

I'm trying to test server response from a few client websites using cURL to retrieve only the header, wrapped in a microtime call to calculate full execution time (for server roundtrip), and the HTTP status code so that myself and the client can be aware of any issues.

I need to call cURL by server IP with the host defined there as I want to be 100% sure to eliminate DNS server downtime - I'm using another script to make sure my DNS copies are up to date, so that's not an issue.

I'm using the following code which is working on 90% of servers, but the odd few are rejecting with 400 and 404 codes despite being accessible in a browser.

    // 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);

The code is wrapped within an Object and all relevant variables are correctly passed, trimmed, and sanitised. Because I need to call the server IP, this is passed as CURLOPT_URL, with the URL passed in the Header. I've tried setting the referer, but this didn't help.


  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dry9192 2013-05-12 08:58

    If all you need is the first line from header, then using curl is overkill. Using socket functions you can close connection immediately after receiving first line with status code:

    $conn = fsockopen($this->ip, 80);
    $nl = "
    fwrite($conn, 'GET / HTTP/1.1'.$nl);
    foreach($header as $h) {
        fwrite($conn, $h.$nl);
    fwrite($conn, $nl);
    $statusLine = fgets($conn);
    $status = substr($statusLine, 9, 3);
    解决 无用
    打赏 举报

相关推荐 更多相似问题