PHP get_headers() reports different headers than CURL

后端 未结 2 1530
谎友^
谎友^ 2021-01-05 01:40

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         


        
2条回答
  •  有刺的猬
    2021-01-05 02:23

    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.

提交回复
热议问题