PHP get_headers()报告的头与CURL报告的头不同

PHP get_headers()报告的头与CURL报告的头不同,php,curl,http-headers,Php,Curl,Http Headers,为什么get_headers()返回的结果可能与通过CURL获取的结果不同?这是我的密码: header("Content-type: text/plain"); $url = 'http://www.foxbusiness.com/index.html'; echo "get_headers() headers:\n\n"; $headers = get_headers($url); print_r($headers); echo "\n\nCURL headers\n\n"; $curl

为什么
get_headers()
返回的结果可能与通过CURL获取的结果不同?这是我的密码:

header("Content-type: text/plain");
$url = 'http://www.foxbusiness.com/index.html';

echo "get_headers() headers:\n\n";
$headers = get_headers($url);
print_r($headers);

echo "\n\nCURL headers\n\n";
$curl = curl_init();
curl_setopt_array( $curl, array(
    CURLOPT_HEADER => true,
    CURLOPT_NOBODY => true,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_URL => $url ) );
$headers = explode( "\n", curl_exec( $curl ) );
curl_close( $curl );
print_r($headers);
结果是:

get_headers() headers:

Array
(
    [0] => HTTP/1.0 403 Forbidden
    [1] => Server: AkamaiGHost
    [2] => Mime-Version: 1.0
    [3] => Content-Type: text/html
    [4] => Content-Length: 283
    [5] => Expires: Fri, 31 Aug 2012 07:29:14 GMT
    [6] => Date: Fri, 31 Aug 2012 07:29:14 GMT
    [7] => Connection: close
)


CURL headers

Array
(
    [0] => HTTP/1.1 200 OK
    [1] => Server: Apache
    [2] => X-FoxNews-EdgeTTL: 2m
    [3] => Content-Type: text/html;charset=UTF-8
    [4] => Cache-Control: max-age=64
    [5] => Date: Fri, 31 Aug 2012 07:29:14 GMT
    [6] => Connection: keep-alive
    [7] => 
    [8] => 
)

默认情况下,
get_headers
将执行get请求,而您将cURL配置为执行HEAD请求。首先,通过放置不同的

此外,服务器似乎期望有一个用户代理,因此请确保将其添加到流上下文中

以下方面应起作用:

stream_context_set_default(
    array(
        'http' => array(
            'method' => 'HEAD',
            'user_agent' => "PHP"
        )
    )
);


请注意,
stream\u context\u set\u default
会修改全局默认流上下文,因此,一旦调用上述函数,对使用此流包装器的其他方法的任何调用现在都将执行HEAD请求。例如,
file\u get\u contents
get\u headers
不允许通过参数向函数提供自定义流上下文。换句话说,请确保在获取标题后将方法更改回GET。

在获取标题之前添加其他用户代理标题:

stream_context_set_default(
    array(
        'http' => array(
            'method' => 'HEAD',
            'header' => "User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_4) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.79 Safari/537.1\r\n"
        )
    )
);
而且,还可以指定HEAD,因为您只需要头。通过此更改,您可以获得正确的标题

输出

get_headers() headers:

Array
(
    [0] => HTTP/1.0 200 OK
    [1] => Server: Apache
    [2] => X-FoxNews-EdgeTTL: 2m
    [3] => Content-Type: text/html;charset=UTF-8
    [4] => Cache-Control: max-age=76
    [5] => Date: Fri, 31 Aug 2012 07:53:24 GMT
    [6] => Connection: close
)


CURL headers

Array
(
    [0] => HTTP/1.1 200 OK
    [1] => Server: Apache
    [2] => X-FoxNews-EdgeTTL: 2m
    [3] => Content-Type: text/html;charset=UTF-8
    [4] => Cache-Control: max-age=76
    [5] => Date: Fri, 31 Aug 2012 07:53:24 GMT
    [6] => Connection: keep-alive
    [7] => 
    [8] => 
)

@PhpMyCoder I包含了上面的代码。我不知道如何知道它发送了什么头。OP在哪里调用example.com?