context+php,复习PHP-语言参考-Context选项和参数

1.在file_get_contents和fopen作为参数调用。

resource fopen ( string $filename , string $mode [, bool $use_include_path = false [, resource $context ]] )

string file_get_contents ( string $filename [, bool $use_include_path = false [, resource $context [, int $offset = -1[, int $maxlen ]]]] )

注意这两个函数都有一个context参数,类型是resource

而context是怎么整理并放置进去的呢? 简单的案例

如下:

$opts = array(

'http'=>array(

'method'=>"GET",

'header'=>"Accept-language: en\r\n" .

"Cookie: foo=bar\r\n"

)

);

$context = stream_context_create($opts);

/* Sends an http request to www.example.com

with additional headers shown above */

$fp = fopen('http://www.example.com', 'r', false, $context);

fpassthru($fp);

fclose($fp);

?>

具体的用法就是将一个数组形式的参数列表用create方法创建,即可在fopen和file_get_contents中使用了。

以下是官方的解释:

简单例:

$options = [

"socket" =>[

"bindto"=>"0:7000", //”127.0.0.120:7001”

],

];

$context = stream_context_create($options);

echo file_get_contents("http://www.baidu.com",false,$context);

?>

这里是以本机7000端口去访问获取百度的首页内容。

例3获取一个页面并发送POST数据:

$postdata = http_build_query(

array(

'var1' => 'some content',

'var2' => 'doh'

)

);

$opts = array('http' =>

array(

'method'  => 'POST',

'header'  => 'Content-type: application/x-www-form-urlencoded',

'content' => $postdata

)

);

$context = stream_context_create($opts);

$result = file_get_contents('http://example.com/submit.php', false, $context);

?>

例4

$data = array ('foo' => 'bar');

$data = http_build_query($data);

$opts = array (

'http' => array (

'method' => 'POST',

'header'=> "Content-type: application/x-www-form-urlencoded\r\n" .

"Content-Length: " . strlen($data) . "\r\n",

'content' => $data

),

);

$context = stream_context_create($opts);

$html = file_get_contents('http://www.example.com', false, $context);

echo $html;

?>

本章对context的讲解主要用于各种协议内容的获取,POST GET 和相关的设置,包含curl,file_get_contents,fopen,soket,还有各种http https ftp ssl 等。 具体在实际运用中再详细研究。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值