上下文选项
介绍:
PHP提供了多种上下文选项和参数,可用于所有的文件系统或数据流封装协议。上下文由
stream_context_create()
创建。选项可通过stream_context_set_option()
设置,参数可用stream_context_set_params()
设置。
多种上下文:(请参考php手册)
获取上下文:
//http上下文
$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);
//socket 上下文
// connect to the internet using the '192.168.0.100' IP and port '7000'
$opts = array(
'socket' => array(
'bindto' => '192.168.0.100:7000',
),
);
// create the context...
$context = stream_context_create($opts);
...
file_get_content 的 get 请求:
<?php
/**
* GET 请求
* @param [string] $url 请求链接
* @param [string] $method 请求方法
* @param [array] $get_data 携带的参数
* @return [array] $result 返回获取的内容
*/
function send_get($url,$method, $get_data) {
$getdata = http_build_query($get_data);
$options = array(
'http' => array(
'method' => 'GET',
'header' => 'Content-type:application/x-www-form-urlencoded',
)
);
$context = stream_context_create($options);
$result = file_get_contents($url.$getdata, false, $context);
return $result;
}
$get_data = array(
'username' => 'username',
'password' => 'password'
);
$res =send_get('http://www.test.com/index.php?name=act',$get_data);
var_dump($res);
die;
file_get_content 的 post 请求:
<?php
/**
* POST 请求
* @param [string] $url 请求链接
* @param [array] $post_data 携带的参数
* @return [array] $result 返回获取的内容
*/
function send_post($url,$post_data) {
$postdata = http_build_query($post_data);
$options = array(
'http' => array(
'method' => 'POST',//注意要大写
'header' => 'Content-type:application/x-www-form-urlencoded',
'content' => $postdata
)
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
return $result;
}
$post_data = array(
'username' => 'username',
'password' => 'password'
);
$res =send_post('http://www.test.com/index.php?name=act',$post_data);
var_dump($res);
die;