dongxun4110 2015-12-03 18:07 采纳率: 0%
浏览 103
已采纳

如何标题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).

  • 写回答

1条回答 默认 最新

  • dtyw10299 2015-12-03 20:10
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试
  • ¥20 问题请教!vue项目关于Nginx配置nonce安全策略的问题
  • ¥15 教务系统账号被盗号如何追溯设备
  • ¥20 delta降尺度方法,未来数据怎么降尺度
  • ¥15 c# 使用NPOI快速将datatable数据导入excel中指定sheet,要求快速高效
  • ¥15 再不同版本的系统上,TCP传输速度不一致
  • ¥15 高德地图2.0 版本点聚合中Marker的位置无法实时更新,如何解决呢?
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题