stream_context_create

stream_context_create(?array $options = null, ?array $params = null): resource

流上下文创建:file_get_contents/fopen 网络进阶用法的底座——按 ['wrapper']['option'] 二维关联数组预设 HTTP 方法/请求头/超时/User-Agent 等参数,之后一切带 $context 的流调用自动继承。

C C23

C23
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>

/* C 标准库没有 HTTP 客户端:「上下文」只是一包配置,
 * 由 libcurl 这类库在真正发起请求时消费。 */
typedef struct {
    const char *method;
    const char *user_agent;
    double timeout;
} http_options;

int main(void) {
    http_options opts = {"POST", "codeabc-agent/1.0", 2.0};
    printf("%s %s\n", opts.method, opts.user_agent);

    /* 127.0.0.1:59999 上无监听服务,connect() 必以 ECONNREFUSED
     * 失败——确定性的派生事实。 */
    int fd = socket(AF_INET, SOCK_STREAM, 0);
    struct sockaddr_in addr = {0};
    addr.sin_family = AF_INET;
    addr.sin_port = htons(59999);
    inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
    int ok = connect(fd, (struct sockaddr *)&addr, sizeof(addr)) == 0;
    printf("connect-failed: %s\n", ok ? "false" : "true");
    close(fd);
    return 0;
}
输出
POST codeabc-agent/1.0
connect-failed: true

C++ C++26

C++26
#include <iostream>
#include <string>
#include <chrono>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>

// C++ 同样没有标准 HTTP 客户端:「上下文」只是一包配置,
// 稍后交给网络库消费。
struct HttpOptions {
    std::string method;
    std::string user_agent;
    std::chrono::milliseconds timeout;
};

int main() {
    HttpOptions opts{"POST", "codeabc-agent/1.0", std::chrono::milliseconds{2000}};
    std::cout << opts.method << ' ' << opts.user_agent << '\n';

    // 127.0.0.1:59999 上无监听服务,connect() 必以 ECONNREFUSED
    // 失败——确定性的派生事实。
    int fd = socket(AF_INET, SOCK_STREAM, 0);
    sockaddr_in addr{};
    addr.sin_family = AF_INET;
    addr.sin_port = htons(59999);
    inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
    bool ok = connect(fd, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) == 0;
    std::cout << "connect-failed: " << (ok ? "false" : "true") << '\n';
    close(fd);
}
输出
POST codeabc-agent/1.0
connect-failed: true

C# v11.0.100

v11.0.100
using System.Net;
using System.Net.Sockets;

// .NET 的流上下文对应物分三层:SocketsHttpHandler(连接级)、
// HttpClient(超时/重试)、HttpRequestMessage(请求级头)。
var handler = new SocketsHttpHandler { ConnectTimeout = TimeSpan.FromMilliseconds(500) };
using var client = new HttpClient(handler) { Timeout = TimeSpan.FromSeconds(2) };
client.DefaultRequestHeaders.UserAgent.ParseAdd("codeabc-agent/1.0");
Console.WriteLine("POST codeabc-agent/1.0");

// 127.0.0.1:59999 上无监听服务,连接尝试抛 SocketException——确定性的派生事实。
try
{
    using var tcp = new TcpClient();
    tcp.Connect(IPAddress.Loopback, 59999);
    Console.WriteLine("connect-failed: false");
}
catch (SocketException)
{
    Console.WriteLine("connect-failed: true");
}
输出
POST codeabc-agent/1.0
connect-failed: true

Go v1.27.4

v1.27.4
package main

import (
	"fmt"
	"net"
	"net/http"
	"time"
)

func main() {
	// Go 的流上下文对应物:http.Client(客户端级超时)
	// 加上 http.Request 上的请求级头。
	client := &http.Client{Timeout: 2 * time.Second}
	req, _ := http.NewRequest("POST", "http://127.0.0.1:59999/submit", nil)
	req.Header.Set("User-Agent", "codeabc-agent/1.0")
	fmt.Println(req.Method, req.Header.Get("User-Agent"))

	// 127.0.0.1:59999 上无监听服务,拨号必以 ECONNREFUSED
	// 失败——确定性的派生事实。
	conn, err := net.DialTimeout("tcp", "127.0.0.1:59999", 500*time.Millisecond)
	fmt.Println("connect-failed:", err != nil)
	if conn != nil {
		conn.Close()
	}
	_ = client // 真实请求时由它携带 Timeout
}
输出
POST codeabc-agent/1.0
connect-failed: true

Java v27.0.1

v27.0.1
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.time.Duration;

public class Main {
    public static void main(String[] args) throws Exception {
        // Java 的流上下文对应物:HttpClient(连接级)+
        // HttpRequest builder(请求级)。
        HttpClient client = HttpClient.newBuilder()
                .connectTimeout(Duration.ofMillis(500))
                .build();
        HttpRequest request = HttpRequest.newBuilder(URI.create("http://127.0.0.1:59999/submit"))
                .timeout(Duration.ofSeconds(2))
                .header("User-Agent", "codeabc-agent/1.0")
                .POST(HttpRequest.BodyPublishers.noBody())
                .build();
        System.out.println(request.method() + " " + request.headers().firstValue("User-Agent").orElse(""));

        // 127.0.0.1:59999 上无监听服务,connect 抛
        // ConnectException——确定性的派生事实。
        try (java.net.Socket socket = new java.net.Socket()) {
            socket.connect(new java.net.InetSocketAddress("127.0.0.1", 59999), 500);
            System.out.println("connect-failed: false");
        } catch (java.net.ConnectException e) {
            System.out.println("connect-failed: true");
        }
    }
}
输出
POST codeabc-agent/1.0
connect-failed: true

JavaScript v26.13.1

v26.13.1
// JS 的流上下文对应物:传给 fetch/http.request 的选项对象
//(method、headers、signal)。
const opts = {
  method: 'POST',
  headers: { 'User-Agent': 'codeabc-agent/1.0' },
  signal: AbortSignal.timeout(2000),
};
console.log(`${opts.method} ${opts.headers['User-Agent']}`);

// 127.0.0.1:59999 上无监听服务,连接以 ECONNREFUSED
// 报错——确定性的派生事实。
const net = require('node:net');
const sock = net.connect(59999, '127.0.0.1');
sock.on('connect', () => { console.log('connect-failed: false'); sock.end(); });
sock.on('error', () => console.log('connect-failed: true'));
输出
POST codeabc-agent/1.0
connect-failed: true

PHP v8.6.0

v8.6.0
$opts = [
    'http' => [
        'method' => 'POST',
        'header' => "Content-Type: application/x-www-form-urlencoded\r\n",
        'content' => 'name=codeabc&lang=php',
        'timeout' => 2.0,
        'user_agent' => 'codeabc-agent/1.0',
    ],
    'ssl' => ['verify_peer' => true],
];
$context = stream_context_create($opts);
echo $opts['http']['method'], ' ', $opts['http']['user_agent'], "\n";
// 127.0.0.1:59999 上无监听服务,连接必失败——派生事实,不触外部网络。
$fp = @stream_socket_client('tcp://127.0.0.1:59999', $errno, $errstr, 0.5, STREAM_CLIENT_CONNECT, $context);
var_dump($fp === false);
echo 'connect-failed', "\n";
输出
POST codeabc-agent/1.0
bool(true)
connect-failed

Python v3.15.2

v3.15.2
import http.client
import socket

# Python 的流上下文对应物:http.client/requests 的构造参数
#(headers 与 timeout 都是参数)。
conn = http.client.HTTPConnection("127.0.0.1", 59999, timeout=0.5)
cfg = {"method": "POST", "headers": {"User-Agent": "codeabc-agent/1.0"}}
print(cfg["method"], cfg["headers"]["User-Agent"])

# 127.0.0.1:59999 上无监听服务,create_connection 抛
# ConnectionRefusedError——确定性的派生事实。
try:
    socket.create_connection(("127.0.0.1", 59999), timeout=0.5)
    print("connect-failed: false")
except OSError:
    print("connect-failed: true")
输出
POST codeabc-agent/1.0
connect-failed: true

Rust v1.99.1

v1.99.1
use std::net::TcpStream;
use std::time::Duration;

fn main() {
    // Rust 的流上下文对应物:reqwest builder 上的类型化配置
    //(ClientBuilder + RequestBuilder 分层)。
    let opts = ("POST", "codeabc-agent/1.0", Duration::from_secs(2));
    println!("{} {}", opts.0, opts.1);

    // 127.0.0.1:59999 上无监听服务,connect() 返回
    // ECONNREFUSED——确定性的派生事实。
    let failed = TcpStream::connect("127.0.0.1:59999").is_err();
    println!("connect-failed: {}", if failed { "true" } else { "false" });
}
输出
POST codeabc-agent/1.0
connect-failed: true

TypeScript v26.13.1

v26.13.1
// TS 的流上下文对应物:传给 fetch/http.request 的选项对象
//(method、headers、signal)。
interface RequestContext {
  method: string;
  headers: Record<string, string>;
  signal: AbortSignal;
}
const opts: RequestContext = {
  method: 'POST',
  headers: { 'User-Agent': 'codeabc-agent/1.0' },
  signal: AbortSignal.timeout(2000),
};
console.log(`${opts.method} ${opts.headers['User-Agent']}`);

// 127.0.0.1:59999 上无监听服务,连接以 ECONNREFUSED
// 报错——确定性的派生事实。
const net = require('node:net');
const sock = net.connect(59999, '127.0.0.1');
sock.on('connect', () => { console.log('connect-failed: false'); sock.end(); });
sock.on('error', () => console.log('connect-failed: true'));
输出
POST codeabc-agent/1.0
connect-failed: true

语言差异说明

PHP:流上下文 = 传给 fopen/file_get_contents/stream_socket_client 等一切带 $context 参数调用的「预设配置包」;options 是 ['wrapper']['option'] => value 的二维关联数组(http/ssl/ftp/socket 各一节),params 放通知回调等流参数;形参结构错误自 8.0 起抛 ValueError/TypeError(手册 Errors)。

真实 HTTP 调用:$ctx = stream_context_create(['http' => [...]]) 后 file_get_contents($url, false, $ctx)——POST 的 content 要先 http_build_query 编码、多行 header 用 CRLF 分隔;https 场景的选项挂在 http 键下(https wrapper 复用 http 选项,手册用户注)。

C/C++:stdlib 无 HTTP 客户端——「上下文」只是一包装配置的结构体,真正生效要靠第三方库(libcurl)或手写 socket。

Go:http.Client{Timeout}(客户端级)+ http.Transport(传输级)分层对应;单次请求再叠 http.NewRequest 的 Header。

Java:HttpClient.Builder(连接级)+ HttpRequest.Builder(请求级)两层,与 options/params 分层同构。

C#:SocketsHttpHandler(连接级)+ HttpClient(超时/重试)+ HttpRequestMessage(请求级)三层配置。

Python:http.client.HTTPConnection(host, port, timeout) 构造即上下文;requests 库则收进 requests.get(..., headers=, timeout=) 参数。

JS/TS:fetch 的第二个参数对象(method/headers/signal)就是一次性的 context;Node http.request 的 options 对象同理。

Rust:reqwest 的 ClientBuilder(客户端级)+ RequestBuilder(请求级)链式配置,与 PHP 二维 options 分层对应;std 只有 TcpStream,无 HTTP 层。

超时语义:PHP 的 timeout 选项是 socket 超时(float 秒);真实生产调用务必显式设置——默认值取自 default_socket_timeout(默认 60 秒)。