您好!欢迎访问家园网-www.jy.wang!

家园网

请详细讲解php中stream_context_create()‌函数。

网络 作者:本站 点击:

PHP stream_context_create() 函数详解

词源分解

stream_context_create 由三部分组成:

  • stream:表示数据流,指代输入/输出通道

  • context:意为上下文环境

  • create:表示创建动作

组合含义为"创建流操作上下文环境"

功能

用于创建并配置资源流上下文,可自定义各种流操作(如HTTP请求、文件操作等)的行为规则,包括:

  • 设置HTTP请求头/方法/超时

  • 配置代理服务器

  • 启用SSL/TLS加密

  • 处理重定向

语法结构

resource stream_context_create(
    [array $options = []],
    [array $params = []]
)

参数详解

1. $options (必需)

二维关联数组,结构为$arr['wrapper']['option'] = $value,常用包装器:

包装器作用域典型配置项
httpHTTP请求methodheaderproxy
httpsHTTPS请求verify_peerallow_self_signed
ftpFTP操作overwriteresume_pos
socket套接字bindtobacklog

HTTP常用选项示例‌:

$options = [
    'http' => [
        'method' => "POST",
        'header' => "Content-Type: application/json\r\n",
        'content' => json_encode(['key'=>'value']),
        'timeout' => 10
    ]
];

2. $params (可选)

关联数组格式$arr['parameter'] = $value,标准参数包括:

  • notification:流通知回调函数

  • options:包装器特定选项

返回值

返回resource类型的上下文资源,可传递给:

  • file_get_contents()

  • fopen()

  • stream_socket_client()等函数

函数示例

示例1:GET请求带自定义头

$opts = [
    'http' => [
        'method' => "GET",
        'header' => "Accept-language: en\r\nCookie: foo=bar\r\n"
    ]
];
$context = stream_context_create($opts);
$data = file_get_contents('http://example.com', false, $context);

示例2:POST表单提交

$postdata = http_build_query(['name'=>'test','age'=>25]);
$options = [
    'http' => [
        'method'  => 'POST',
        'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
        'content' => $postdata
    ]
];
$context = stream_context_create($options);
$result = file_get_contents('http://example.com/api', false, $context);

示例3:使用代理服务器

$opts = [
    'http' => [
        'proxy' => 'tcp://127.0.0.1:8080',
        'request_fulluri' => true
    ]
];
$context = stream_context_create($opts);
$data = file_get_contents('http://example.com', false, $context);

输出特性

  1. 不直接输出‌:仅返回上下文资源,需配合其他函数使用

  2. 输出控制‌:通过目标函数(如file_get_contents())决定输出方式

  3. 二进制安全‌:支持处理图片等二进制数据

补充说明

安全注意事项

  • 生产环境应限制allow_url_fopen配置

  • 敏感操作建议使用cURL替代

性能优化

  • 复用上下文对象减少创建开销

  • 对频繁请求使用持久连接

调试技巧

可通过stream_context_get_options()查看当前配置

标签: