PHP stream_context_create 函数作用与原型
该函数的主要作用是创建并返回一个流上下文资源,通过应用各种选项来定制数据流的行为。这些选项可用于 fopen()、file_get_contents() 等过程中,实现超时设置、代理服务器配置、指定 HTTP 请求方式以及自定义头信息等特殊需求。
函数原型定义如下:resource stream_context_create ([ array $options [, array $params ]] )。其中 $options 数组用于指定特定协议(如 http、https)的配置项,$params 数组通常用于传递额外的参数。
在实际开发中,可以通过不同的场景来使用该函数,以下列举了几个典型用例。
第一个例子展示了如何发送带有自定义头信息的 HTTP GET 请求。
<?php
$opts = 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.jb51.net
with additional headers shown above */
$fp = fopen('https://www.jb51.net', 'r', false, $context);
fpassthru($fp);
fclose($fp);
?> 第二个例子进一步演示了头信息的设置方式,特别是当需要设置多个头字段时。
<?php
$opts = array(
'method'=>"GET",
'header'=>"Accept-language: en\r\n" .
"Cookie: foo=bar\r\n"
)
);
$context = stream_context_create($opts);
?> You would setup the header this way:
<?php
$opts = array(
'method'=>"GET",
'header'=>array("Accept-language: en",
"Cookie: foo=bar",
"Custom-Header: value")
)
);
$context = stream_context_create($opts);
?> 第三个例子展示了如何通过代理服务器发起请求。
<?php
$opts = array('http' => array('proxy' => 'tcp://127.0.0.1:8080', 'request_fulluri' => true));
$context = stream_context_create($opts);
$data = file_get_contents('https://www.jb51.net', false, $context);
echo $data;
?> 第四个例子演示了如何使用 stream_context_create 发送包含文件上传的 POST 请求。
<?php
function do_post_request($url, $postdata, $files = null)
{
$data = "";
$boundary = "---------------------".substr(md5(rand(0,32000)), 0, 10);
//Collect Postdata
foreach($postdata as $key => $val)
{
$data .= "--$boundary\n";
$data .= "Content-Disposition: form-data; name=\"".$key."\"\n\n".$val."\n";
}
$data .= "--$boundary\n";
//Collect Filedata
foreach($files as $key => $file)
{
$fileContents = file_get_contents($file['tmp_name']);
$data .= "Content-Disposition: form-data; name=\"{$key}\"; filename=\"{$file['name']}\"\n";
$data .= "Content-Type: image/jpeg\n";
$data .= "Content-Transfer-Encoding: binary\n\n";
$data .= $fileContents."\n";
$data .= "--$boundary--\n";
}
$params = array('http' => array(
'method' => 'POST',
'header' => 'Content-Type: multipart/form-data; boundary='.$boundary,
'content' => $data
));
$ctx = stream_context_create($params);
$fp = fopen($url, 'rb', false, $ctx);
if (!$fp) {
throw new Exception("Problem with $url, $php_errormsg");
}
$response = @stream_get_contents($fp);
if ($response === false) {
throw new Exception("Problem reading data from $url, $php_errormsg");
}
return $response;
}
//set data (in this example from post)
//sample data
$postdata = array(
'name' => $_POST['name'],
'age' => $_POST['age'],
'sex' => $_POST['sex']
);
//sample image
$files['image'] = $_FILES['image'];
do_post_request("https://www.jb51.net", $postdata, $files);
?>