如何标题stream_context_create?

I have the following code:

$options = array(
    'http' => array(
        'header' => "Content-type: text/html
",
        'method' => 'POST'
    ),
);

$context = stream_context_create($options);
$response = file_get_contents($url, false, $context);

This is not giving the appropriate result (no result at all), since the equivalent curl is:

function curl($url) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HEADER, true);
    curl_setopt($ch, CURLOPT_POST, 1);
    $data = curl_exec($ch);
    curl_close($ch);

    $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    echo $httpcode;

    return $data;
}

curl($url);

actually gives the actual result.

Since i'd like to avoid curl in production server, i'd really like the file_get_contents to work. To debug this, I have decided to examine the header for both curl and file_get_contents. In the curl code above, you can notice an echo, which prints the header:

HTTP/1.0 411 Length Required Content-Type: text/html; charset=UTF-8 Content-Length: 1564 Date: Thu, 03 Dec 2015 18:00:25 GMT Server: GFE/2.0

I'd like to do the same for file_get_contents to examine its headers and hope fully see what is wrong. (you could point out what's wrong yourself if you like).

Something like this should work:

<?php

$url = 'http://example.com/';
$data = ''; // empty post

$options = array(
    'http' => array(
    'header' => "Content-type: text/html
Content-Length: " . strlen($data) . "
",
    'method' => 'POST'
    ),
);

$context = stream_context_create($options);
$fp      = fopen($url, 'r', false, $context);
$meta    = stream_get_meta_data($fp);

if (!$fp) {
    echo "Failed!";
} else {
    echo "Success";
    $response = stream_get_contents($fp);
}

fclose($fp);
var_dump($meta);

To get the stream meta data, you will need to switch from file_get_contents to fopen. It makes no difference as under the hood, PHP will connect and issue the response in the same way (using the http:// wrapper).

If php.ini is set to disable allow_url_fopen, the both file_get_contents and fopen will be affected and won't be able to open remote URLs. As long as this isn't the case, fopen of a URL will work the same way as file_get_contents; using fopen just gives you access to the stream which you can then call stream_get_meta_data on.