HTTP Message
Note: The HTTP message library is part of the Berlioz ecosystem but is available as a standalone package:
berlioz/http-message.
You can find it on Packagist.
You can use it independently of the framework, in any PHP application.
Berlioz HTTP Message is a PHP library that implements the PSR-7 (HTTP message interfaces) and PSR-17 (HTTP Factories) standards.
PSR references
See the PSR documentation:
- PSR-7 (HTTP message interfaces): https://www.php-fig.org/psr/psr-7/
- PSR-17 (HTTP Factories): https://www.php-fig.org/psr/psr-17/
Factory
Only one factory class implements PSR-17:
\Berlioz\Http\Message\HttpFactory
To help you, the factory is split into several traits:
\Berlioz\Http\Message\Factory\RequestFactoryTrait\Berlioz\Http\Message\Factory\ResponseFactoryTrait\Berlioz\Http\Message\Factory\ServerRequestFactoryTrait\Berlioz\Http\Message\Factory\StreamFactoryTrait\Berlioz\Http\Message\Factory\UploadedFileFactoryTrait\Berlioz\Http\Message\Factory\UriFactoryTrait
Reading a stream
Info: Since version 3.5
getContents() reads from the current cursor to the end. After read(2) on a stream containing abcdef,
it returns cdef. A second getContents() returns ''.
Writing also advances the cursor. If you write x at the end of a stream and immediately call getContents(),
you now get '' instead of x. For a seekable stream, use (string) $stream to read the whole body, or call
$stream->rewind() before $stream->getContents(). A non-seekable stream can only return its remaining bytes.
A stream created from a string now starts at position zero. If you create a stream from abc and immediately
write de, you get dec instead of abcde: write() replaces bytes at the cursor. To append, call
$stream->seek(0, SEEK_END) before writing. This also applies when middleware adds markup to a response
created with new Response($html).
Specialized Streams
Beyond the base Stream class, several specialized stream implementations are available:
Stream\MemoryStream: In-memory stream backed byphp://memoryStream\FileStream: Opens a file on disk as a streamStream\PhpInputStream: Cachesphp://input(readable only once) for safe multiple readsStream\GzStream: Gzip-compressed stream using thezlibextensionStream\GzFileStream: Opens a gzip-compressed file on diskStream\Base64Stream: Transparent base64 encoding via PHP stream filtersStream\AppendStream: Concatenates multiple streams into a single read-only virtual streamStream\MultipartStream: Builds MIME multipart bodies (e.g. formultipart/form-datarequests)
Example with MultipartStream:
use Berlioz\Http\Message\Stream\MultipartStream;
$multipart = new MultipartStream();
$multipart->addElements(['field1' => 'value1', 'field2' => 'value2']);
$multipart->addFile('file', '/path/to/file.pdf');
$contentType = 'multipart/form-data; boundary=' . $multipart->getBoundary();
Info: Since version 3.4
MultipartStream validates what frames the parts. An invalid boundary, part header name or part header value
throws an InvalidArgumentException, and nothing is added to the stream. In field names and file names, ", \,
CR and LF are percent-encoded (%22, %5C, %0D, %0A), so they cannot change the structure read by the
receiver.
Body parsers
The Message class includes a body parser registry. Built-in parsers handle common content types:
application/jsonviaJsonParserapplication/x-www-form-urlencodedviaFormUrlEncodedParsermultipart/form-dataviaFormDataParser
You can register custom parsers for any MIME type:
use Berlioz\Http\Message\Message;
Message::addBodyParser('application/xml', MyXmlParser::class);
The parser class must implement Berlioz\Http\Message\Parser\ParserInterface.
Content-type suffixes are handled automatically (e.g. application/vnd.api+json resolves to the json parser).
Malformed bodies
Info: Since version 3.4
getParsedBody() throws a Berlioz\Http\Message\Exception\MalformedBodyException when the body cannot be used:
invalid JSON, or a parsed value that is neither an array, an object nor null (e.g. a JSON string "text").
The exception extends RuntimeException, and getHttpMessage() returns the message whose body is malformed.
A custom parser should throw this exception when it cannot parse the contents; getParsedBody() attaches the message
to it. In an HTTP application, the framework answers with a 400 Bad Request when the body of the incoming request
is malformed (see HTTP exceptions). A malformed body of another message, such as a response
received from an upstream API, remains a server error (500).
HTTP/1 emission
Info: Since version 3.4
Berlioz\Http\Message\Validator\Http1ResponseValidator checks that any PSR-7 response, from this library or another
one, can be sent as a valid HTTP/1 message. Validate the response before sending anything, so that an invalid response
is never sent halfway:
use Berlioz\Http\Message\Exception\InvalidResponseException;
use Berlioz\Http\Message\Validator\Http1ResponseValidator;
try {
$head = (new Http1ResponseValidator())->validate($response);
} catch (InvalidResponseException $exception) {
// Nothing has been sent yet: log the error and send another response
throw $exception;
}
header($head->statusLine);
foreach ($head->headers as $name => $values) {
foreach ($values as $i => $value) {
// Pass the status code, so PHP does not change it (e.g. with a "Location" header)
header(sprintf('%s: %s', $name, $value), 0 === $i, $head->statusCode);
}
}
The validator checks:
- Protocol version: a digit, optionally followed by a dot and a digit (
1.0,1.1,2…). “HTTP/1” names the format produced, a status line andName: valuelines as expected byheader(): the web server translates it to the protocol negotiated with the client, so2is accepted. Rules specific to HTTP/2 and HTTP/3 are not checked - Status code: from 100 to 599
- Reason phrase: no control character, except the horizontal tab
- Header names: an RFC 9110 token; pseudo-headers such as
:statusare rejected - Header values: no control character except the horizontal tab, and no leading or trailing space or tab; empty values are allowed
An invalid field throws a Berlioz\Http\Message\Exception\InvalidResponseException, which extends
InvalidArgumentException. The validator never corrects a value and never reads the body.
On success, validate() returns an Http1ResponseHead with three read-only properties:
statusLine: the status line, e.g.HTTP/1.1 200 OKstatusCode: the status codeheaders: the header values by name, in the order of the response; each value stays separate (e.g. oneSet-Cookieper cookie)
Messages of this library remove the leading and trailing spaces and tabs of header values when they are built. Apart from that, they stay permissive, because they also hold received data, such as incoming requests or responses of an HTTP client: they only reject CR, LF and NUL in header values, and accept any status code, protocol version and pseudo-header (e.g. when an HTTP client session is replayed from a HAR file). Only an HTTP/1 emission rejects the other values.
HttpApp::print() uses this validator before sending a response (see After the response).
Additional methods
Some methods are provided beyond the PSR-7/PSR-17 standards:
Request::HTTP_METHOD_*constants — HTTP method names (Request::HTTP_METHOD_GET,Request::HTTP_METHOD_POST…), includingRequest::HTTP_METHOD_QUERYsince version 3.4ServerRequest::getServerParam(string $name, mixed $default = null): mixed— single server parameter accessServerRequest::getQueryParam(string $name, mixed $default = null): mixed— single query parameter accessServerRequest::isAjaxRequest(): bool— detects AJAX requestsUri::getQueryValue(string $name, mixed $default = null): mixed— extract a single query parameter from the URIUri::withAddedQuery(string $query): static— merge additional query parametersUri::withoutQuery(string $name): static— remove a query parameterUploadedFile::getHash(string $algo = 'sha1'): string— compute a file content hashUploadedFile::getMediaType(): ?string— server-side MIME detection viafinfo