php stream context create,php stream_context_create函数

这段代码展示了如何使用PHP的stream_context_create函数创建HTTP请求的上下文。例子中,首先定义了请求选项,包括HTTP方法、头部信息(如cookie)和代理设置,然后创建了数据流上下文,并用于fopen函数打开URL。通过stream_context_create,可以发送GET或POST请求,同时控制请求头和代理。最后,使用fpassthru和fclose处理响应数据并关闭文件指针。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

函数原型:resource stream_context_create ([ array $options [, array $params ]] )

看个实例

//定义options数组

$opts=array

(

'http'=>array

(

'method'=>"get",

'header'=>"accept-language: enrn"."cookie: foo=barrn"

)

);

//创建数据流上下文

$context=stream_context_create($opts);

/*向指定地址发送http请求

请求中包含附加的头部信息*/

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

//输出文件指针处的所有数据

fpassthru($fp);

//关闭文件

fclose($fp);

/*

该代码的输出结果为:即请求的cookie值

array

(

[foo] => bar

)

*/

实例二

$default_opts=array

(

'http'=>array

(

'method'=>"get",

'header'=>"accept-language: enrn"."cookie: foo=bar",

'proxy'=>"tcp://10.54.1.39:8000"

)

);

$alternate_opts=array

(

'http'=>array

(

'method'=>"post",

'header'=>"content-type: application/x-www-form-urlencodedrn"."content-length: " . strlen("baz=bomb"),

'content'=>"baz=bomb"

)

);

$default=stream_context_get_default($default_opts);

$alternate=stream_context_create($alternate_opts);

/* sends a regular get request to proxy server at 10.54.1.39

* for www.example.com using context options specified in $default_opts

*/

readfile('http://www.example.com');

/* sends a post request directly to www.example.com

* using context options specified in $alternate_opts

*/

readfile('http://www.example.com', false, $alternate);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值