stream_context_create

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

Creates a stream context — the foundation for advanced file_get_contents/fopen network usage: preset HTTP method, headers, timeout, user-agent and more in a ['wrapper']['option'] nested array, which every stream call taking $context then inherits.

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 has no HTTP client in the standard library: a "context" is just
 * a bundle of config that a library like libcurl would consume. */
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);

    /* No server listens on 127.0.0.1:59999, so connect() fails
     * with ECONNREFUSED — a deterministic derived fact. */
    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;
}
Output
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++ has no standard HTTP client either: a "context" is just a
// config bundle handed to a networking library later.
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';

    // No server listens on 127.0.0.1:59999, so connect() fails
    // with ECONNREFUSED — a deterministic derived fact.
    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);
}
Output
POST codeabc-agent/1.0
connect-failed: true

C# v11.0.100

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

// The .NET analog of a stream context lives in three layers:
// SocketsHttpHandler (connection), HttpClient (timeout/retry),
// HttpRequestMessage (per-request headers).
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");

// No server listens on 127.0.0.1:59999, so the connect attempt
// throws SocketException — a deterministic derived fact.
try
{
    using var tcp = new TcpClient();
    tcp.Connect(IPAddress.Loopback, 59999);
    Console.WriteLine("connect-failed: false");
}
catch (SocketException)
{
    Console.WriteLine("connect-failed: true");
}
Output
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() {
	// The Go analog of a stream context: http.Client (per-client
	// timeout) plus per-request headers on 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"))

	// No server listens on 127.0.0.1:59999, so the dial fails
	// with ECONNREFUSED — a deterministic derived fact.
	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 // would carry Timeout into the real request
}
Output
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 {
        // The Java analog of a stream context: an HttpClient (connection
        // level) plus an HttpRequest builder (per-request level).
        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(""));

        // No server listens on 127.0.0.1:59999, so connect
        // throws ConnectException — a deterministic derived fact.
        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");
        }
    }
}
Output
POST codeabc-agent/1.0
connect-failed: true

JavaScript v26.13.1

v26.13.1
// The JS analog of a stream context: an options object (method,
// headers, signal) passed to fetch or http.request.
const opts = {
  method: 'POST',
  headers: { 'User-Agent': 'codeabc-agent/1.0' },
  signal: AbortSignal.timeout(2000),
};
console.log(`${opts.method} ${opts.headers['User-Agent']}`);

// No server listens on 127.0.0.1:59999, so the connect attempt
// errors with ECONNREFUSED — a deterministic derived fact.
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'));
Output
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";
// No server listens on 127.0.0.1:59999, so the connect attempt
// fails deterministically — no external network is touched.
$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";
Output
POST codeabc-agent/1.0
bool(true)
connect-failed

Python v3.15.2

v3.15.2
import http.client
import socket

# The Python analog of a stream context: constructor arguments on
# http.client / requests (headers and timeout as parameters).
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"])

# No server listens on 127.0.0.1:59999, so create_connection
# raises ConnectionRefusedError — a deterministic derived fact.
try:
    socket.create_connection(("127.0.0.1", 59999), timeout=0.5)
    print("connect-failed: false")
except OSError:
    print("connect-failed: true")
Output
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() {
    // The Rust analog of a stream context: a typed config on the
    // reqwest builder (ClientBuilder + RequestBuilder layers).
    let opts = ("POST", "codeabc-agent/1.0", Duration::from_secs(2));
    println!("{} {}", opts.0, opts.1);

    // No server listens on 127.0.0.1:59999, so connect()
    // returns ECONNREFUSED — a deterministic derived fact.
    let failed = TcpStream::connect("127.0.0.1:59999").is_err();
    println!("connect-failed: {}", if failed { "true" } else { "false" });
}
Output
POST codeabc-agent/1.0
connect-failed: true

TypeScript v26.13.1

v26.13.1
// The TS analog of a stream context: an options object (method,
// headers, signal) passed to fetch or http.request.
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']}`);

// No server listens on 127.0.0.1:59999, so the connect attempt
// errors with ECONNREFUSED — a deterministic derived fact.
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'));
Output
POST codeabc-agent/1.0
connect-failed: true

Language differences

PHP: a stream context is a preset config bundle passed to every call that takes a $context argument (fopen, file_get_contents, stream_socket_client, ...); options is a two-level assoc array ['wrapper']['option'] => value (one section each for http/ssl/ftp/socket) and params holds stream parameters like the notification callback; malformed structures throw ValueError/TypeError since 8.0 (manual Errors).

Real HTTP calls: $ctx = stream_context_create(['http' => [...]]) then file_get_contents($url, false, $ctx) — the POST body must be http_build_query-encoded first and multi-line headers joined with CRLF; for https the options still live under the http key (the https wrapper reuses the http options, manual user note).

C/C++: no HTTP client in stdlib — a "context" is just a struct of config; something like libcurl or a hand-rolled socket actually consumes it.

Go: http.Client{Timeout} (per-client) + http.Transport (transport) mirror the layered context; per-request headers stack on http.NewRequest.

Java: HttpClient.Builder (connection level) + HttpRequest.Builder (request level) — isomorphic to the options/params split.

C#: three layers — SocketsHttpHandler (connection), HttpClient (timeout/retry), HttpRequestMessage (request).

Python: http.client.HTTPConnection(host, port, timeout) constructor args are the context; the requests library folds it into requests.get(..., headers=, timeout=) parameters.

JS/TS: fetch's second argument object (method/headers/signal) is a one-shot context; Node's http.request options object is the same idea.

Rust: reqwest's ClientBuilder (client level) + RequestBuilder (request level) chained config maps to PHP's two-level options; std only has TcpStream, no HTTP layer.

Timeout semantics: PHP's timeout option is a socket timeout in float seconds; always set it explicitly in production — the default comes from default_socket_timeout (60 seconds by default).