如何用流获取标题?

时间:2016-08-02 11:58:22

标签: php http stream http-headers

考虑这个功能:

function use_fopen($url, $make_post_field, $headers = '') {

    $context = array(
                       'http' => array(
                       'method'  => 'POST',
                       'timeout' => '60',
                       'content' => $make_post_field)
    );
    $header = "Content-type: application/x-www-form-urlencoded\r\n";
    if (!empty($headers)) {
        foreach ($headers as $head) {
                 $header.="$head\r\n";
        }
    }

    $context['http']['header'] = $header;
    $context = stream_context_create($context);

    //$contents = @file_get_contents($url, null, $context);
    $fp = fopen($url, 'r', false, $context);

    $stream_meta_data = @stream_get_meta_data($fp);
    print_r($stream_meta_data );
    fclose($fp);
}

我使用这样的功能:

$headers = array ('baz: bar');
$data = array ('foo' => 'bar', 'bar' => 'baz');
$data = http_build_query($data);
print(use_fopen("http://www.example.com/phpinfo.php", $data, $headers));

由于目标网址是phpinfo,我可以验证$_POST['foo']是否设置为bar和

CONTENT_TYPE = application/x-www-form-urlencoded

HTTP_FOO = baz

所以看起来上下文工作正常,但是当我使用

$stream_meta_data = @stream_get_meta_data($fp);
print_r($stream_meta_data );

我得到了

Array
(
[timed_out] => 
[blocked] => 1
[eof] => 
[wrapper_data] => Array
    (
        [0] => HTTP/1.1 200 OK
        [1] => Date: Tue, 02 Aug 2016 11:46:36 GMT
        [2] => Server: Apache
        [3] => Connection: close
        [4] => Content-Type: text/html; charset=UTF-8
    )

[wrapper_type] => http
[stream_type] => tcp_socket/ssl
[mode] => r
[unread_bytes] => 8061
[seekable] => 
[uri] => http://wwwexample.com/phpinfo.php
)

为什么内容类型错误,而且这里没有显示实际为标题的HTTP_FOO?下面的变化也没有帮助。我该怎么办?获取自定义标题和正确的内容类型?

$contents = @file_get_contents($url, null, $context);
print_r(get_headers($url));

我搜索了SO并找到了这个How to get HTTP response headers after POST request in PHP?,但正如我所说,我尝试了stream_get_meta_data($fp)get_headers($url),但我没有获得自定义标题。我该怎么办?

1 个答案:

答案 0 :(得分:1)

从谷歌找到你的帖子,因为我遇到了和你一样的问题。我用函数stream_context_set_default解决了它。我以为我会把它发布给谷歌的下一个绊脚石,或者你还需要一个解决方案。