Core\Http\Client::openStream
Core\Http\Client::openStream(
Core\Http\Method $method,
string|Core\Http\Target $url,
{…},
): Core\Http\StreamSends a request to another server and lets your program read the answer while it is still arriving.
The call returns as soon as the status and the headers have arrived. The result is a Core\Http\Stream: status() and header() read them, and one of four methods reads the body. events() gives server-sent events, lines() gives one line at a time, chunks() gives the bytes, and saveTo() writes the body to a file. The body can be read only once.
You choose the method, for example Core\Http\Method::Post. The URL is checked before anything is sent. Two more options limit a slow body. idle is the longest pause between two pieces. maxDuration is the most time the whole body may take.
Good to know: the examples run without a network, so every request in them throws an error before it is sent. They show a feed of live events, the two time limits, and a job that imports orders one line at a time.
Parameters
$methodCore\Http\MethodThe HTTP method to send, as aCore\Http\Methodcase. APostor aPatchwith retries but withoutretryIdempotencyKeythrows an error before the first attempt. The methodspostandpatchgive a compile error for the same mistake.$urlstring|Core\Http\TargetWhere the request goes. It is a URL that the program wrote, or aCore\Http\TargetfromCore\Http::allowUrl. AtaintedURL comes from outside the program, such as from a request. It is not allowed here. Check it withCore\Http::allowUrlfirst.
Options
deadlineCore\Time\DurationoptionalThe time limit until the status and headers arrive. It covers the connection, every redirect, every retry and every wait between retries. It does not cover the body.idleandmaxDurationlimit the body. If it is not given, the runtime's[http.client] deadlineis used. There is no way to write a call with no deadline.connectTimeoutCore\Time\DurationoptionalHow long the connection alone may take. This time is part ofdeadline, and is not added to it.headersarray<secret string>optionalExtra request headers, by name. Asecretvalue is a value the program must keep hidden, such as an API key. It is allowed here, because a credential must reach the API it is for. Ataintedvalue is not allowed. The runtime adds its own headers as well.followRedirectsuintoptionalHow many redirects to follow. If it is not given, the runtime's[http.client] max_redirectsis used, and its default is0. Each redirect is checked against the outbound policy again, and its address is approved again.retryAttemptsuintoptionalThe total number of attempts, including the first. The default is1, which means no retry.0throws an error. All attempts share one deadline, andretryBackoffsets the wait between them.retryBackoffCore\Time\DurationoptionalThe base delay between retries. The delay doubles after each retry. Each wait is a random time up to that delay, which is called full jitter. If it is not given, it is100ms.retryIdempotencyKeystringoptionalSent as theIdempotency-Keyheader, with the same value on every attempt. It is required forpostandpatchwhenretryAttemptsis given. Every other method also accepts it.jsonmixedoptionalThe value to send asapplication/json. It is encoded once for the whole call. Asecretinside it is sent, as it is in a header. Anullvalue sends the JSON documentnull, not an empty body.formarray<secret tainted string>optionalThe fields to send asapplication/x-www-form-urlencoded, by name.bodysecret tainted string|secret tainted bytes|Core\Http\PartoptionalThe bytes to send exactly as given, with the media type incontentType. Only one ofjson,form,bodyandmultipartmay be given. A call that gives two of them does not compile. A call togetorheadthat gives one of them does not compile either.contentTypestringoptionalThe media type ofbody. It has no effect withoutbody, so giving it alone is a compile error.multipartarray<secret tainted string|Core\Http\Part>optionalThe parts to send asmultipart/form-data, by name.identityCore\Http\IdentityoptionalThe client certificate to send when the server asks for one. Create it withCore\Http\Identity::read. Nothing is sent to a server that does not ask. Two different identities never share a pooled connection. A call without an identity does not share one with a call that has one.tlsCastringoptionalThe PEM certificates to trust for this call. They replace[tls.client] rootscertificates. The URL's host must be in theanchorsgrant ofcapabilities.tls. If it is not, the call throws an error before it connects.tlsPinstring|array<string>optionalOnesha256//<base64>public-key pin, or several. The server is accepted if the hash of its SubjectPublicKeyInfo matches one of them. No certificate chain is checked. Use this to reach a server with a self-signed certificate. The host must be in thepingrant.tlsVerifyHostbooloptionalIf it isfalse, the chain is still checked, and only the name check is skipped. The host must be in theany_namegrant.tlsVerifybooloptionalIf it isfalse, neither the chain nor the name is checked. The handshake signature is still checked, so the server has the key it sent. But nothing shows whose key it is. The host must be in theinsecuregrant.tlsMinVersionstringoptionalThe lowest TLS version this call allows,"1.2"or"1.3". It needs no grant, because it can only make the call stricter. A value below the runtime's[tls.client] min_versionthrows an error.connectTostringoptionalThe IP address to connect to. The URL's host is not looked up, but the certificate is still checked against that host. The host must be in thenet.connect_togrant. The deployment's address policy checks this address like a looked-up one. With aCore\Http\Targetas the URL, this option throws an error, because the target already has its approved addresses.redirectToHttpbooloptionalIf it istrue, a redirect fromhttpsto plainhttpmay be followed. The redirect's host must also be in thenet.downgradegrant. If it is not given, such a redirect throws an error. So a server cannot turn off a call's TLS with oneLocationheader. This option does not affect a plainhttpURL that you request directly.idleCore\Time\DurationoptionalThe longest time the body may be silent after the status and headers arrive. If it is not given, the runtime's[http.client] idleis used. There is no way to turn this limit off.maxDurationCore\Time\DurationoptionalThe longest time the whole body may take. This limit stops a server that sends one byte at a time, just often enough to pass theidlecheck. If it is not given, the runtime's[http.client] max_durationis used.
Return value
Returns Core\Http\Stream. A Core\Http\Stream. Its status(), header() and headers() methods return the status and headers. Read the body with exactly one of events(), lines(), chunks() and saveTo().
Errors
RuntimeErrorThe URL is not allowed. It is not a URL, its scheme is nothttporhttps, or it has no host. Ornet.connectdoes not grant the host. Or the host resolves to a loopback, private, link-local or unspecified address thatnet.internaldoes not list. An option is out of range. Adeadline,connectTimeoutorretryBackoffis not a positive duration. OrretryAttemptsis zero. A header name or value contains a control byte, which would end the line early. Anhttpsserver sent a certificate that does not verify against[tls.client] roots, or againsttlsCawhen it is given. Or the certificate is not valid for that name. For these two cases, the message says which setting fixes it. Or the reply is not HTTP, or it is larger than the limit for one request. AnidleormaxDurationis not a positive duration. Before the first attempt, this method checks two mistakes that the other methods find at compile time. A body option on aGetor aHeadthrows an error. Retries on aPostor aPatchwithoutretryIdempotencyKeyalso throw an error.TimeoutErrorThedeadlinepassed before the status and headers arrived. It covers the connection, every redirect, every retry and every wait between retries. If a wait would end after the deadline, the error is thrown at once, without waiting.IOErrorThe last attempt could not connect to the approved address. Or the connection failed while the request was sent or the reply was read.
Changelog
| Version | Change |
|---|---|
0.0.6 | Core\Http\Client::openStream opens a streamed request, and Core\Http\TlsInfo->isVerified() checks the certificate. The old names were stream and verified. |
Examples
The examples below run with this configuration file.
# The program may connect to public hosts only.# `internal = []` allows no address on this computer or on a private network.[capabilities.net]internal = []Following live events
<?nvs// Shows how to follow a feed of live events from another server, one event at a time.
// `Core\Http\Client::openStream` returns when the status and the headers have arrived.// 10.0.0.12 is a private address, so the call throws a `RuntimeError` before it sends anything.try { Core\Http\Stream $feed = Core\Http\Client::openStream(Core\Http\Method::Get, 'http://10.0.0.12/orders/live', { headers: ['Accept' => 'text/event-stream'] }); echo 'status: ', $feed->status(), "\n"; // `events()` gives each event when the server has sent all of it. foreach ($feed->events() as Core\Http\Event $event) { echo $event->name() ?? 'message', ': ', $event->data(), "\n"; }} catch (RuntimeError $refused) { echo $refused->message, "\n";}Core\Http\Client::openStream cannot connect to 10.0.0.12: it is private (10/8, 172.16/12, 192.168/16), which `net.internal` does not excepthelp: add `internal = ["10.0.0.12"]` under `[capabilities.net]` in nvs.tomlLimits for a slow reply
<?nvs// Shows the two options that limit how long the body of a streamed reply may take.
// `idle` is the longest pause between two pieces of the body. It must be longer than zero.try { var $quiet = Core\Http\Client::openStream(Core\Http\Method::Get, 'https://203.0.113.10/prices/live', { idle: 0s });} catch (RuntimeError $noPause) { echo $noPause->message, "\n";}
// `maxDuration` is the most time the whole body may take. It must be longer than zero too.try { var $endless = Core\Http\Client::openStream(Core\Http\Method::Get, 'https://203.0.113.10/prices/live', { maxDuration: 0s });} catch (RuntimeError $noTime) { echo $noTime->message, "\n";}Core\Http\Client::openStream: `idle` must be a positive duration, and this one is 0nsCore\Http\Client::openStream: `maxDuration` must be a positive duration, and this one is 0nsImporting orders line by line
<?nvs// Shows a job that imports a large export of orders one line at a time, so the// whole export is never in memory at once.
uint $imported = 0;try { // The export is a `POST` request, and each line of the reply is one order. Core\Http\Stream $export = Core\Http\Client::openStream(Core\Http\Method::Post, 'https://192.168.4.20/exports/orders', { json: ['since' => '2026-09-01'], idle: 30s, maxDuration: 10m }); if ($export->status() == 200) { foreach ($export->lines() as tainted string $line) { // An empty line is not an order. if (Core\Str::length($line) > 0) { $imported = $imported + 1; } } }} catch (RuntimeError $error) { echo 'The export stopped: ', $error->message, "\n";}
// The export server is at a private address, so this prints `imported: 0`.echo 'imported: ', $imported, "\n";The export stopped: Core\Http\Client::openStream cannot connect to 192.168.4.20: it is private (10/8, 172.16/12, 192.168/16), which `net.internal` does not excepthelp: add `internal = ["192.168.4.20"]` under `[capabilities.net]` in nvs.tomlimported: 0