函数名称:stream_context_set_option()
函数描述:stream_context_set_option() 函数设置指定的流上下文选项。
适用版本:PHP 4 >= 4.3.0, PHP 5, PHP 7
语法:bool stream_context_set_option ( resource $stream_or_context , string $wrapper , string $option , mixed $value )
参数:
- $stream_or_context:要设置选项的流或流上下文。可以是资源类型的流或流上下文。
- $wrapper:要设置选项的流的封装器类型。
- $option:要设置的选项名称。
- $value:要设置的选项值。
返回值:成功时返回 true,失败时返回 false。
示例:
- 设置 HTTP 请求头部信息:
$opts = array(
'http' => array(
'method' => 'GET',
'header' => 'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'
)
);
$context = stream_context_create($opts);
stream_context_set_option($context, 'http', 'header', 'Accept-language: en');
// 使用流上下文发送请求
$file = file_get_contents('http://www.example.com', false, $context);
在上面的示例中,我们首先创建了一个包含 HTTP 请求头部信息的选项数组。然后,使用 stream_context_create() 函数创建了一个流上下文。接下来,使用 stream_context_set_option() 函数设置了一个新的 HTTP 请求头部信息。最后,使用 file_get_contents() 函数发送了一个 HTTP GET 请求,并将返回的内容保存在变量 $file 中。
- 设置 SSL 验证选项:
$opts = array(
'ssl' => array(
'verify_peer' => true,
'cafile' => '/path/to/cert.pem',
)
);
$context = stream_context_create($opts);
stream_context_set_option($context, 'ssl', 'verify_peer', false);
// 使用流上下文发送请求
$file = file_get_contents('https://www.example.com', false, $context);
在上面的示例中,我们首先创建了一个包含 SSL 验证选项的选项数组。然后,使用 stream_context_create() 函数创建了一个流上下文。接下来,使用 stream_context_set_option() 函数设置了 SSL 验证选项中的 verify_peer 为 false,即禁用了对服务器证书的验证。最后,使用 file_get_contents() 函数发送了一个 HTTPS 请求,并将返回的内容保存在变量 $file 中。
请注意,示例中的选项数组和流上下文是根据具体需求来设置的,可以根据实际情况进行修改和扩展。