phasync
ClientRequest / sendResponseHeaders

Method

ClientRequest::sendResponseHeaders

Set the response's status and headers.

Description#

public ClientRequest::sendResponseHeaders(
    int $status,
    array $headers = []
): void

A 1xx (100, 103, ...) is an interim response: sent at once, and may be repeated. 101 is sent at once and switches to the raw connection, connection and upgrade being yours to send. Any other status is the final head: held until the body starts, and sendable once.

Parameters#

$status int
$headers array = []

Errors / Exceptions#

ExceptionWhen
HeadersSentExceptionWhen the final head was committed already

Examples#

Example 1An interim 103 and a final 201
use Swerve\ClientRequest;
use Swerve\RequestHandler;

$app = new RequestHandler(function (ClientRequest $request) {
    // A 1xx goes out at once: here 103 Early Hints, while the page is still being made
    $request->sendResponseHeaders(103, ['link' => '</style.css>; rel=preload; as=style']);

    // The final head waits for the first body bytes, and goes out with them
    $request->sendResponseHeaders(201, ['content-type' => 'application/json', 'location' => '/items/7']);
    $request->write('{"id":7}');
});

if (debug_backtrace()) {
    return $app;   // swerve loads this file: it is the application's swerve.php
}

// Run directly: serve the application with swerve, and send it requests
require __DIR__ . '/../serve.php';
serve(__FILE__, ["POST /items HTTP/1.1\r\nHost: example\r\nContent-Length: 0\r\n\r\n"]);
Output
HTTP/1.1 103 Early Hints
link: </style.css>; rel=preload; as=style

HTTP/1.1 201 Created
content-type: application/json
location: /items/7
Server: Swerve
Transfer-Encoding: chunked
Connection: close

8
{"id":7}
0