dongxu1668 2012-08-31 07:33
浏览 121
已采纳

PHP get_headers()报告的标头不同于CURL

How is it possible that get_headers() could possibly return a different result than getting them by CURL? Here is my code:

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

echo "get_headers() headers:

";
$headers = get_headers($url);
print_r($headers);

echo "

CURL headers

";
$curl = curl_init();
curl_setopt_array( $curl, array(
    CURLOPT_HEADER => true,
    CURLOPT_NOBODY => true,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_URL => $url ) );
$headers = explode( "
", curl_exec( $curl ) );
curl_close( $curl );
print_r($headers);

This is the result:

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] => 
)
  • 写回答

2条回答 默认 最新

  • 普通网友 2012-08-31 07:49
    关注

    get_headers will do a GET request by default while you configured cURL to do a HEAD request. Start by making the request identical to what cURL sends by putting a different HTTP stream context using HEAD for the request method.

    Also, the server seems to expect a User Agent, so make sure you either provide user_agent in php.ini or add it to the stream context.

    The following should work:

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

    See http://codepad.viper-7.com/cOO9XS

    Note that stream_context_set_default modifies the global default Stream Context, so any calls to other methods using this stream wrapper will now do HEAD requests once you called the above. Unlike for example, file_get_contents, get_headers does not allow supplying a custom stream context via arguments to the function. In other words, make sure you change the method back to GET after you got the headers.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 Arcgis相交分析无法绘制一个或多个图形
  • ¥15 seatunnel-web使用SQL组件时候后台报错,无法找到表格
  • ¥15 fpga自动售货机数码管(相关搜索:数字时钟)
  • ¥15 用前端向数据库插入数据,通过debug发现数据能走到后端,但是放行之后就会提示错误
  • ¥30 3天&7天&&15天&销量如何统计同一行
  • ¥30 帮我写一段可以读取LD2450数据并计算距离的Arduino代码
  • ¥15 飞机曲面部件如机翼,壁板等具体的孔位模型
  • ¥15 vs2019中数据导出问题
  • ¥20 云服务Linux系统TCP-MSS值修改?
  • ¥20 关于#单片机#的问题:项目:使用模拟iic与ov2640通讯环境:F407问题:读取的ID号总是0xff,自己调了调发现在读从机数据时,SDA线上并未有信号变化(语言-c语言)