user4271704 user4271704 - 1 year ago 101
HTTP Question

How to get header with stream?

Consider this function:

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) {

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

I use the function like this:

$headers = array ('baz: bar');
$data = array ('foo' => 'bar', 'bar' => 'baz');
$data = http_build_query($data);
print(use_fopen("", $data, $headers));

As target url is phpinfo, I can verify that
is set to bar and

CONTENT_TYPE = application/x-www-form-urlencoded

HTTP_FOO = baz

So it seems context is working fine, but when I use

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

I get

[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] =>

why content-type is wrong and HTTP_FOO that is actually a header is not shown here? the change below also did not help. what should I do? to get custom headers and correct content-type?

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

I searched SO and found this How to get HTTP response headers after POST request in PHP? but as I said I tried both
but I don't get my custom headers. what else should I do?

Answer Source

It seems you are confused with request header and response header. You can't send HTTP_FOO header from client and expect it to be in header of server. You need to set it in target script in server side:

header ('HTTP_FOO: Bar');

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download