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 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题