函数名称:stream_context_create()
函数功能:创建一个流上下文
适用版本:所有版本
函数用法: stream_context_create ( array $options = ? , array $params = ? ) : resource
参数说明:
options:一个关联数组,用于设置流上下文的选项。可选参数包括:
params:一个关联数组,用于设置流上下文的额外参数。可选参数包括:
返回值:成功时返回一个资源类型的流上下文,失败时返回false。
示例代码:
// 创建一个HTTP请求的流上下文
$options = array(
'http' => array(
'method' => 'POST',
'header' => 'Content-Type: application/json',
'content' => json_encode(array('name' => 'John')),
),
);
$context = stream_context_create($options);
// 发送HTTP请求
$response = file_get_contents('http://example.com/api', false, $context);
// 创建一个SSL连接的流上下文
$options = array(
'ssl' => array(
'verify_peer' => true,
'cafile' => '/path/to/cert.pem',
),
);
$context = stream_context_create($options);
// 打开一个SSL连接
$socket = stream_socket_client('ssl://example.com:443', $errno, $errstr, 30, STREAM_CLIENT_CONNECT, $context);
if (!$socket) {
die("Failed to connect: $errstr ($errno)");
}
// 其他用法和示例请参考官方文档:https://www.php.net/manual/en/function.stream-context-create.php
注意事项: