PSR-7 (HttpMessage) & PSR-17 (HttpFactory) Implementations
UploadedFile::getClientFullPath()
. PHP 8.1 added a new file upload property (not included in PSR-7)ServerRequestExtended
interface and implementation - Extends standard server request with helpful methodsparse_str()
, but does not convert dots and spaces to '_' by defaultemit(ResponseInterface $response)
- Output response headers and body codePhrase(int|string $code): string
- Get standard code phrase for given HTTP status codefromGlobals(): ServerRequestInterface
getContent(StreamInterface): string
- Get stream contents without affecting pointerfromGlobals(): UriInterface
fromParsed(array): UriInterface
isCrossOrigin(UriInterface $uri1, UriInterface $uri2): bool
parseUrl(string|UriInterface): array
- like php's parse_url
but with bug fixes backported resolve(UriInterface $base, UriInterface $rel): UriInterface
- Converts the relative URI into a new URI that is resolved against the base URI.composer require bdk/http-message
http://bradkent.com/php/httpmessage
Version | http-message | http-factory | php | note |
---|---|---|---|---|
3.x | ^1.1 | ^2.0 | ^1.0 | >= 8.0 | static returns |
2.x | ^1.1 | ^2.0 | ^1.0 | >= 7.2 | self returns |
1.x | ~1.0.1 | -- | >= 5.4 |
Http Message
HTTP messages consist of requests from a client to a server and responses from a server to a client. This interface defines the methods common to each.
Messages are considered immutable; all methods that might change state are implemented such that they retain the internal state of the current message and return an instance that contains the changed state.
getBody(): Psr\Http\Message\StreamInterface
Gets the body of the message.
getHeader(string $name): string[]
Retrieves a message header value by the given case-insensitive name.
This method returns an array of all the header values of the given case-insensitive header name.
getHeaderLine(string $name): string
Retrieves a comma-separated string of the values for a single header.
This method returns all of the header values of the given case-insensitive header name as a string concatenated together using a comma.
NOTE: Not all header values may be appropriately represented using
comma concatenation. For such headers, use getHeader()
instead
and supply your own delimiter when concatenating.
If the header does not appear in the message, this method will return an empty string.
getHeaders(): string[][]
Retrieves all message header values.
The keys represent the header name as it will be sent over the wire, and each value is an array of strings associated with the header.
// Represent the headers as a string
foreach ($message->getHeaders() as $name => $values) {
echo $name . ": " . implode(", ", $values);
}
// Emit headers iteratively:
foreach ($message->getHeaders() as $name => $values) {
foreach ($values as $value) {
header(sprintf('%s: %s', $name, $value), false);
}
}
While header names are not case-sensitive, getHeaders() will preserve the exact case in which headers were originally specified.
getProtocolVersion(): string
Retrieves the HTTP protocol version as a string.
hasHeader(string $name): bool
Checks if a header exists by the given case-insensitive name.
withAddedHeader(string $name, string|string[] $value): static
Return an instance with the specified header values appended to the current value
Existing values for the specified header will be maintained. The new value(s) will be appended to the existing list. If the header did not exist previously, it will be added.
withBody(Psr\Http\Message\StreamInterface $body): static
Return an instance with the specified message body.
withHeader(string $name, string|string[] $value): static
Return an instance with the provided value replacing the specified header.
withoutHeader(string $name): static
Return an instance without the specified header.
withProtocolVersion(string $version): static
Return an instance with the specified HTTP protocol version.
The version string MUST contain only the HTTP version number (e.g., "1.1", "1.0").
Representation of an outgoing, client-side request.
Per the HTTP specification, this class includes properties for each of the following:
Requests are considered immutable; all methods that might change state are implemented such that they retain the internal state of the current message and return an instance that contains the changed state.
__construct(string $method = GET[, Psr\Http\Message\UriInterface|string $uri = ])
Constructor
getMethod(): string
Retrieves the HTTP method of the request.
getRequestTarget(): string
Retrieves the message's request target.
Retrieves the message's request-target either as it will appear (for clients), as it appeared at request (for servers), or as it was specified for the instance (see withRequestTarget()).
In most cases, this will be the origin-form of the composed URI, unless a value was provided to the concrete implementation (see withRequestTarget() below).
If no URI is available, and no request-target has been specifically provided, this method will return the string "/".
getUri(): Psr\Http\Message\UriInterface
Retrieves the URI instance.
withMethod(string $method): static
Return an instance with the provided HTTP method.
Standard methods include: HEAD: Asks for a response identical to that of a GET request, but without the response body. GET: Requests a representation of the specified resource Requests using GET should only retrieve data. POST: Submit an entity to the specified resource, Often causing a change in state or side effects on the server. PUT: Replaces all current representations of the target resource with the request payload. DELETE: Deletes the specified resource. PATCH: Used to apply partial modifications to a resource. CONNECT: Establishes a tunnel to the server identified by the target resource. OPTIONS: Used to describe the communication options for the target resource. TRACE: Performs a message loop-back test along the path to the target resource.
withRequestTarget(string $requestTarget): static
Return an instance with the specific request-target.
If the request needs a non-origin-form request-target — e.g., for specifying an absolute-form, authority-form, or asterisk-form — this method may be used to create an instance with the specified request-target, verbatim.
withUri(Psr\Http\Message\UriInterface $uri[, bool $preserveHost = false]): static
Returns an instance with the provided URI.
This method will update the Host header of the returned request by default if the URI contains a host component. If the URI does not contain a host component, any pre-existing Host header MUST be carried over to the returned request.
You can opt-in to preserving the original state of the Host header by
setting $preserveHost
to true
. When $preserveHost
is set to
true
, this method interacts with the Host header in the following ways:
getBody(): Psr\Http\Message\StreamInterface
Gets the body of the message.
getHeader(string $name): string[]
Retrieves a message header value by the given case-insensitive name.
This method returns an array of all the header values of the given case-insensitive header name.
getHeaderLine(string $name): string
Retrieves a comma-separated string of the values for a single header.
This method returns all of the header values of the given case-insensitive header name as a string concatenated together using a comma.
NOTE: Not all header values may be appropriately represented using
comma concatenation. For such headers, use getHeader()
instead
and supply your own delimiter when concatenating.
If the header does not appear in the message, this method will return an empty string.
getHeaders(): string[][]
Retrieves all message header values.
The keys represent the header name as it will be sent over the wire, and each value is an array of strings associated with the header.
// Represent the headers as a string
foreach ($message->getHeaders() as $name => $values) {
echo $name . ": " . implode(", ", $values);
}
// Emit headers iteratively:
foreach ($message->getHeaders() as $name => $values) {
foreach ($values as $value) {
header(sprintf('%s: %s', $name, $value), false);
}
}
While header names are not case-sensitive, getHeaders() will preserve the exact case in which headers were originally specified.
getProtocolVersion(): string
Retrieves the HTTP protocol version as a string.
hasHeader(string $name): bool
Checks if a header exists by the given case-insensitive name.
withAddedHeader(string $name, string|string[] $value): static
Return an instance with the specified header values appended to the current value
Existing values for the specified header will be maintained. The new value(s) will be appended to the existing list. If the header did not exist previously, it will be added.
withBody(Psr\Http\Message\StreamInterface $body): static
Return an instance with the specified message body.
withHeader(string $name, string|string[] $value): static
Return an instance with the provided value replacing the specified header.
withoutHeader(string $name): static
Return an instance without the specified header.
withProtocolVersion(string $version): static
Return an instance with the specified HTTP protocol version.
The version string MUST contain only the HTTP version number (e.g., "1.1", "1.0").
Http Response
Representation of an outgoing, server-side response.
Per the HTTP specification, this class includes properties for each of the following:
Responses are considered immutable; all methods that might change state are implemented such that they retain the internal state of the current message and return an instance that contains the changed state.
__construct(int $code = 200[, string $reasonPhrase = ])
Constructor
getReasonPhrase(): string
Gets the response reason phrase associated with the status code.
getStatusCode(): int
Gets the response status code.
The status code is a 3-digit integer result code of the server's attempt to understand and satisfy the request.
withStatus(int $code[, string $reasonPhrase = ]): static
Return an instance with the specified status code and, optionally, reason phrase.
If no reason phrase is specified, implementations MAY choose to default to the RFC 7231 or IANA recommended reason phrase for the response's status code.
getBody(): Psr\Http\Message\StreamInterface
Gets the body of the message.
getHeader(string $name): string[]
Retrieves a message header value by the given case-insensitive name.
This method returns an array of all the header values of the given case-insensitive header name.
getHeaderLine(string $name): string
Retrieves a comma-separated string of the values for a single header.
This method returns all of the header values of the given case-insensitive header name as a string concatenated together using a comma.
NOTE: Not all header values may be appropriately represented using
comma concatenation. For such headers, use getHeader()
instead
and supply your own delimiter when concatenating.
If the header does not appear in the message, this method will return an empty string.
getHeaders(): string[][]
Retrieves all message header values.
The keys represent the header name as it will be sent over the wire, and each value is an array of strings associated with the header.
// Represent the headers as a string
foreach ($message->getHeaders() as $name => $values) {
echo $name . ": " . implode(", ", $values);
}
// Emit headers iteratively:
foreach ($message->getHeaders() as $name => $values) {
foreach ($values as $value) {
header(sprintf('%s: %s', $name, $value), false);
}
}
While header names are not case-sensitive, getHeaders() will preserve the exact case in which headers were originally specified.
getProtocolVersion(): string
Retrieves the HTTP protocol version as a string.
hasHeader(string $name): bool
Checks if a header exists by the given case-insensitive name.
withAddedHeader(string $name, string|string[] $value): static
Return an instance with the specified header values appended to the current value
Existing values for the specified header will be maintained. The new value(s) will be appended to the existing list. If the header did not exist previously, it will be added.
withBody(Psr\Http\Message\StreamInterface $body): static
Return an instance with the specified message body.
withHeader(string $name, string|string[] $value): static
Return an instance with the provided value replacing the specified header.
withoutHeader(string $name): static
Return an instance without the specified header.
withProtocolVersion(string $version): static
Return an instance with the specified HTTP protocol version.
The version string MUST contain only the HTTP version number (e.g., "1.1", "1.0").
Representation of an incoming, server-side HTTP request.
Per the HTTP specification, this class includes properties for each of the following:
Additionally, it encapsulates all data as it has arrived to the application from the CGI and/or PHP environment, including:
$_SERVER
.$_COOKIE
)$_GET
, or as parsed via parse_str()
)$_FILES
)$_POST
)$_SERVER
values are treated as immutable, as they represent application
state at the time of request; as such, no methods are provided to allow
modification of those values. The other values provide such methods, as they
can be restored from $_SERVER
or the request body, and may need treatment
during the application (e.g., body parameters may be deserialized based on
content type).
Additionally, this class recognizes the utility of introspecting a request to derive and match additional parameters (e.g., via URI path matching, decrypting cookie values, deserializing non-form-encoded body content, matching authorization headers to users, etc). These parameters are stored in an "attributes" property.
Requests are considered immutable; all methods that might change state are implemented such that they retain the internal state of the current message and return an instance that contains the changed state.
__construct(string $method = GET[, Psr\Http\Message\UriInterface|string $uri = [, array $serverParams = array()]])
Constructor
static fromGlobals(array $parseStrOpts = array()): bdk\HttpMessage\ServerRequest
Instantiate self from superglobals
\bdk\HttpMessage\Utility\ServerRequest::fromGlobals
insteadgetAttribute(string $name[, mixed $default = null]): mixed
Retrieve a single derived request attribute.
getAttributes(): mixed[]
Retrieve attributes derived from the request.
The request "attributes" may be used to allow injection of any parameters derived from the request: e.g., the results of path match operations; the results of decrypting cookies; the results of deserializing non-form-encoded message bodies; etc. Attributes will be application and request specific, and CAN be mutable.
getCookieParams(): array
Get Cookie values
getParsedBody(): null|array|object
Get $_POST data
getQueryParams(): array
Get $_GET data
getServerParams(): array
Get $_SERVER values
getUploadedFiles(): array
Retrieve normalized file upload data.
This method returns upload metadata in a normalized tree, with each leaf an instance of Psr\Http\Message\UploadedFileInterface.
registerMediaTypeParser(string $contentType, callable $callable): static
Register media type parser.
Define a custom body parser for a specific media type.
withAttribute(string $name, mixed $value): static
Return an instance with the specified derived request attribute.
withCookieParams(array $cookies): static
Return an instance with the specified cookies.
withoutAttribute(string $name): static
Return an instance that removes the specified derived request attribute.
withParsedBody(null|array|object $data): static
Return an instance with the specified body parameters.
withQueryParams(array $query): static
Return an instance with the specified query string arguments.
withUploadedFiles(array $uploadedFiles): static
Create a new instance with the specified uploaded files.
getMethod(): string
Retrieves the HTTP method of the request.
getRequestTarget(): string
Retrieves the message's request target.
Retrieves the message's request-target either as it will appear (for clients), as it appeared at request (for servers), or as it was specified for the instance (see withRequestTarget()).
In most cases, this will be the origin-form of the composed URI, unless a value was provided to the concrete implementation (see withRequestTarget() below).
If no URI is available, and no request-target has been specifically provided, this method will return the string "/".
getUri(): Psr\Http\Message\UriInterface
Retrieves the URI instance.
withMethod(string $method): static
Return an instance with the provided HTTP method.
Standard methods include: HEAD: Asks for a response identical to that of a GET request, but without the response body. GET: Requests a representation of the specified resource Requests using GET should only retrieve data. POST: Submit an entity to the specified resource, Often causing a change in state or side effects on the server. PUT: Replaces all current representations of the target resource with the request payload. DELETE: Deletes the specified resource. PATCH: Used to apply partial modifications to a resource. CONNECT: Establishes a tunnel to the server identified by the target resource. OPTIONS: Used to describe the communication options for the target resource. TRACE: Performs a message loop-back test along the path to the target resource.
withoutHeader(string $name): static
Return an instance without the specified header.
withRequestTarget(string $requestTarget): static
Return an instance with the specific request-target.
If the request needs a non-origin-form request-target — e.g., for specifying an absolute-form, authority-form, or asterisk-form — this method may be used to create an instance with the specified request-target, verbatim.
withUri(Psr\Http\Message\UriInterface $uri[, bool $preserveHost = false]): static
Returns an instance with the provided URI.
This method will update the Host header of the returned request by default if the URI contains a host component. If the URI does not contain a host component, any pre-existing Host header MUST be carried over to the returned request.
You can opt-in to preserving the original state of the Host header by
setting $preserveHost
to true
. When $preserveHost
is set to
true
, this method interacts with the Host header in the following ways:
getBody(): Psr\Http\Message\StreamInterface
Gets the body of the message.
getHeader(string $name): string[]
Retrieves a message header value by the given case-insensitive name.
This method returns an array of all the header values of the given case-insensitive header name.
getHeaderLine(string $name): string
Retrieves a comma-separated string of the values for a single header.
This method returns all of the header values of the given case-insensitive header name as a string concatenated together using a comma.
NOTE: Not all header values may be appropriately represented using
comma concatenation. For such headers, use getHeader()
instead
and supply your own delimiter when concatenating.
If the header does not appear in the message, this method will return an empty string.
getHeaders(): string[][]
Retrieves all message header values.
The keys represent the header name as it will be sent over the wire, and each value is an array of strings associated with the header.
// Represent the headers as a string
foreach ($message->getHeaders() as $name => $values) {
echo $name . ": " . implode(", ", $values);
}
// Emit headers iteratively:
foreach ($message->getHeaders() as $name => $values) {
foreach ($values as $value) {
header(sprintf('%s: %s', $name, $value), false);
}
}
While header names are not case-sensitive, getHeaders() will preserve the exact case in which headers were originally specified.
getProtocolVersion(): string
Retrieves the HTTP protocol version as a string.
hasHeader(string $name): bool
Checks if a header exists by the given case-insensitive name.
withAddedHeader(string $name, string|string[] $value): static
Return an instance with the specified header values appended to the current value
Existing values for the specified header will be maintained. The new value(s) will be appended to the existing list. If the header did not exist previously, it will be added.
withBody(Psr\Http\Message\StreamInterface $body): static
Return an instance with the specified message body.
withHeader(string $name, string|string[] $value): static
Return an instance with the provided value replacing the specified header.
withProtocolVersion(string $version): static
Return an instance with the specified HTTP protocol version.
The version string MUST contain only the HTTP version number (e.g., "1.1", "1.0").
Extends standard server request with helpful methods
static fromServerRequest(Psr\Http\Message\ServerRequestInterface $serverRequest): ServerRequestExtendedInterface
Create a ServerRequestExtended object from ServerRequest
If a ServerRequestExtendedInterface
instance is passed to this method,
Implementation should return it unmodified.
getCookieParam(string $key[, mixed $default = null]): mixed
Fetch cookie value from cookies sent by the client to the server.
getMediaType(): string|null
Get serverRequest media type, if known.
Parses the Content-Type header and returns the "media type"
example: Content-Type: multipart/form-data; Charset=UTF-8; boundary=ExampleBoundaryString
getMediaType()
will return "multipart/form-data"
getMediaTypeParams(): string[]
Get serverRequest media type params, if known.
Parses and returns the parameters found after the "media type" in the Content-Type header.
example: Content-Type: multipart/form-data; Charset=UTF-8; boundary=ExampleBoundaryString
getMediaTypeParams()
will return
[
'charset' => 'utf-8',
'boundary' => 'ExampleBoundaryString'
]
getParam(string $key[, string $default = null]): mixed
Fetch request parameter value from body or query string (in that order).
getParams(): array
Fetch associative array of body and query string parameters.
getParsedBodyParam(string $key[, mixed $default = null]): mixed
Fetch parameter value from request body.
$default
if not setgetQueryParam(string $key[, mixed $default = null]): mixed
Fetch parameter value from query string.
$default
if not setgetServerParam(string $key[, mixed $default = null]): mixed
Retrieve a server parameter.
$default
if not setisSecure(): bool
Is this a secured request?
isXhr(): bool
Is this an XHR (aka ajax) request?
withAttributes(array<string,mixed> $attributes): static
Create a new instance with the specified attributes.
This method allows setting multiple derived request attributes as described in getAttributes().
This method is implemented in such a way as to retain the immutability of the message, and returns an instance that has the upserted attributes.
__construct(string $method = GET[, Psr\Http\Message\UriInterface|string $uri = [, array $serverParams = array()]])
Constructor
static fromGlobals(array $parseStrOpts = array()): bdk\HttpMessage\ServerRequest
Instantiate self from superglobals
\bdk\HttpMessage\Utility\ServerRequest::fromGlobals
insteadgetAttribute(string $name[, mixed $default = null]): mixed
Retrieve a single derived request attribute.
getAttributes(): mixed[]
Retrieve attributes derived from the request.
The request "attributes" may be used to allow injection of any parameters derived from the request: e.g., the results of path match operations; the results of decrypting cookies; the results of deserializing non-form-encoded message bodies; etc. Attributes will be application and request specific, and CAN be mutable.
getCookieParams(): array
Get Cookie values
getParsedBody(): null|array|object
Get $_POST data
getQueryParams(): array
Get $_GET data
getServerParams(): array
Get $_SERVER values
getUploadedFiles(): array
Retrieve normalized file upload data.
This method returns upload metadata in a normalized tree, with each leaf an instance of Psr\Http\Message\UploadedFileInterface.
registerMediaTypeParser(string $contentType, callable $callable): static
Register media type parser.
Define a custom body parser for a specific media type.
withAttribute(string $name, mixed $value): static
Return an instance with the specified derived request attribute.
withBody(Psr\Http\Message\StreamInterface $body): static
Return an instance with the specified message body.
withCookieParams(array $cookies): static
Return an instance with the specified cookies.
withoutAttribute(string $name): static
Return an instance that removes the specified derived request attribute.
withParsedBody(null|array|object $data): static
Return an instance with the specified body parameters.
withQueryParams(array $query): static
Return an instance with the specified query string arguments.
withUploadedFiles(array $uploadedFiles): static
Create a new instance with the specified uploaded files.
getMethod(): string
Retrieves the HTTP method of the request.
getRequestTarget(): string
Retrieves the message's request target.
Retrieves the message's request-target either as it will appear (for clients), as it appeared at request (for servers), or as it was specified for the instance (see withRequestTarget()).
In most cases, this will be the origin-form of the composed URI, unless a value was provided to the concrete implementation (see withRequestTarget() below).
If no URI is available, and no request-target has been specifically provided, this method will return the string "/".
getUri(): Psr\Http\Message\UriInterface
Retrieves the URI instance.
withMethod(string $method): static
Return an instance with the provided HTTP method.
Standard methods include: HEAD: Asks for a response identical to that of a GET request, but without the response body. GET: Requests a representation of the specified resource Requests using GET should only retrieve data. POST: Submit an entity to the specified resource, Often causing a change in state or side effects on the server. PUT: Replaces all current representations of the target resource with the request payload. DELETE: Deletes the specified resource. PATCH: Used to apply partial modifications to a resource. CONNECT: Establishes a tunnel to the server identified by the target resource. OPTIONS: Used to describe the communication options for the target resource. TRACE: Performs a message loop-back test along the path to the target resource.
withoutHeader(string $name): static
Return an instance without the specified header.
withRequestTarget(string $requestTarget): static
Return an instance with the specific request-target.
If the request needs a non-origin-form request-target — e.g., for specifying an absolute-form, authority-form, or asterisk-form — this method may be used to create an instance with the specified request-target, verbatim.
withUri(Psr\Http\Message\UriInterface $uri[, bool $preserveHost = false]): static
Returns an instance with the provided URI.
This method will update the Host header of the returned request by default if the URI contains a host component. If the URI does not contain a host component, any pre-existing Host header MUST be carried over to the returned request.
You can opt-in to preserving the original state of the Host header by
setting $preserveHost
to true
. When $preserveHost
is set to
true
, this method interacts with the Host header in the following ways:
getBody(): Psr\Http\Message\StreamInterface
Gets the body of the message.
getHeader(string $name): string[]
Retrieves a message header value by the given case-insensitive name.
This method returns an array of all the header values of the given case-insensitive header name.
getHeaderLine(string $name): string
Retrieves a comma-separated string of the values for a single header.
This method returns all of the header values of the given case-insensitive header name as a string concatenated together using a comma.
NOTE: Not all header values may be appropriately represented using
comma concatenation. For such headers, use getHeader()
instead
and supply your own delimiter when concatenating.
If the header does not appear in the message, this method will return an empty string.
getHeaders(): string[][]
Retrieves all message header values.
The keys represent the header name as it will be sent over the wire, and each value is an array of strings associated with the header.
// Represent the headers as a string
foreach ($message->getHeaders() as $name => $values) {
echo $name . ": " . implode(", ", $values);
}
// Emit headers iteratively:
foreach ($message->getHeaders() as $name => $values) {
foreach ($values as $value) {
header(sprintf('%s: %s', $name, $value), false);
}
}
While header names are not case-sensitive, getHeaders() will preserve the exact case in which headers were originally specified.
getProtocolVersion(): string
Retrieves the HTTP protocol version as a string.
hasHeader(string $name): bool
Checks if a header exists by the given case-insensitive name.
withAddedHeader(string $name, string|string[] $value): static
Return an instance with the specified header values appended to the current value
Existing values for the specified header will be maintained. The new value(s) will be appended to the existing list. If the header did not exist previously, it will be added.
withHeader(string $name, string|string[] $value): static
Return an instance with the provided value replacing the specified header.
withProtocolVersion(string $version): static
Return an instance with the specified HTTP protocol version.
The version string MUST contain only the HTTP version number (e.g., "1.1", "1.0").
Extends standard server request with helpful methods
static fromServerRequest(Psr\Http\Message\ServerRequestInterface $serverRequest): ServerRequestExtendedInterface
Create a ServerRequestExtended object from ServerRequest
If a ServerRequestExtendedInterface
instance is passed to this method,
Implementation should return it unmodified.
getCookieParam(string $key[, mixed $default = null]): mixed
Fetch cookie value from cookies sent by the client to the server.
getMediaType(): string|null
Get serverRequest media type, if known.
Parses the Content-Type header and returns the "media type"
example: Content-Type: multipart/form-data; Charset=UTF-8; boundary=ExampleBoundaryString
getMediaType()
will return "multipart/form-data"
getMediaTypeParams(): string[]
Get serverRequest media type params, if known.
Parses and returns the parameters found after the "media type" in the Content-Type header.
example: Content-Type: multipart/form-data; Charset=UTF-8; boundary=ExampleBoundaryString
getMediaTypeParams()
will return
[
'charset' => 'utf-8',
'boundary' => 'ExampleBoundaryString'
]
getParam(string $key[, string $default = null]): mixed
Fetch request parameter value from body or query string (in that order).
getParams(): array
Fetch associative array of body and query string parameters.
getParsedBodyParam(string $key[, mixed $default = null]): mixed
Fetch parameter value from request body.
$default
if not setgetQueryParam(string $key[, mixed $default = null]): mixed
Fetch parameter value from query string.
$default
if not setgetServerParam(string $key[, mixed $default = null]): mixed
Retrieve a server parameter.
$default
if not setisSecure(): bool
Is this a secured request?
isXhr(): bool
Is this an XHR (aka ajax) request?
registerMediaTypeParser(string $contentType, callable $callable): static
Register media type parser.
Define a custom body parser for a specific media type.
Implementation MUST be implemented in such a way that
getParsedBody()
will utilize registered parsers if
parsed-body not explicitly set
withAttributes(array<string,mixed> $attributes): static
Return an instance with the specified derived request attributes.
This method allows setting multiple derived request attributes as described in getAttributes().
This method MUST be implemented in such a way as to retain the immutability of the message, and MUST return an instance that has the upserted attributes.
getAttribute(string $name[, mixed $default = null]): mixed
Retrieve a single derived request attribute.
Retrieves a single derived request attribute as described in getAttributes(). If the attribute has not been previously set, returns the default value as provided.
This method obviates the need for a hasAttribute() method, as it allows specifying a default value to return if the attribute is not found.
getAttributes(): array
Retrieve attributes derived from the request.
The request "attributes" may be used to allow injection of any parameters derived from the request: e.g., the results of path match operations; the results of decrypting cookies; the results of deserializing non-form-encoded message bodies; etc. Attributes will be application and request specific, and CAN be mutable.
getCookieParams(): array
Retrieve cookies.
Retrieves cookies sent by the client to the server.
The data MUST be compatible with the structure of the $_COOKIE superglobal.
getParsedBody(): null|array|object
Retrieve any parameters provided in the request body.
If the request Content-Type is either application/x-www-form-urlencoded or multipart/form-data, and the request method is POST, this method MUST return the contents of $_POST.
Otherwise, this method may return any results of deserializing the request body content; as parsing returns structured content, the potential types MUST be arrays or objects only. A null value indicates the absence of body content.
getQueryParams(): array
Retrieve query string arguments.
Retrieves the deserialized query string arguments, if any.
getUri()->getQuery()
or from the QUERY_STRING
server param.getServerParams(): array
Retrieve server parameters.
Retrieves data related to the incoming request environment, typically derived from PHP's $_SERVER superglobal. The data IS NOT REQUIRED to originate from $_SERVER.
getUploadedFiles(): array
Retrieve normalized file upload data.
This method returns upload metadata in a normalized tree, with each leaf an instance of Psr\Http\Message\UploadedFileInterface.
These values MAY be prepared from $_FILES or the message body during instantiation, or MAY be injected via withUploadedFiles().
withAttribute(string $name, mixed $value): static
Return an instance with the specified derived request attribute.
This method allows setting a single derived request attribute as described in getAttributes().
This method MUST be implemented in such a way as to retain the immutability of the message, and MUST return an instance that has the updated attribute.
withCookieParams(array $cookies): static
Return an instance with the specified cookies.
The data IS NOT REQUIRED to come from the $_COOKIE superglobal, but MUST be compatible with the structure of $_COOKIE. Typically, this data will be injected at instantiation.
This method MUST NOT update the related Cookie header of the request instance, nor related values in the server params.
This method MUST be implemented in such a way as to retain the immutability of the message, and MUST return an instance that has the updated cookie values.
withoutAttribute(string $name): static
Return an instance that removes the specified derived request attribute.
This method allows removing a single derived request attribute as described in getAttributes().
This method MUST be implemented in such a way as to retain the immutability of the message, and MUST return an instance that removes the attribute.
withParsedBody(null|array|object $data): static
Return an instance with the specified body parameters.
These MAY be injected during instantiation.
If the request Content-Type is either application/x-www-form-urlencoded or multipart/form-data, and the request method is POST, use this method ONLY to inject the contents of $_POST.
The data IS NOT REQUIRED to come from $_POST, but MUST be the results of deserializing the request body content. Deserialization/parsing returns structured data, and, as such, this method ONLY accepts arrays or objects, or a null value if nothing was available to parse.
As an example, if content negotiation determines that the request data is a JSON payload, this method could be used to create a request instance with the deserialized parameters.
This method MUST be implemented in such a way as to retain the immutability of the message, and MUST return an instance that has the updated body parameters.
withQueryParams(array $query): static
Return an instance with the specified query string arguments.
These values SHOULD remain immutable over the course of the incoming request. They MAY be injected during instantiation, such as from PHP's $_GET superglobal, or MAY be derived from some other value such as the URI. In cases where the arguments are parsed from the URI, the data MUST be compatible with what PHP's parse_str() would return for purposes of how duplicate query parameters are handled, and how nested sets are handled.
Setting query string arguments MUST NOT change the URI stored by the request, nor the values in the server params.
This method MUST be implemented in such a way as to retain the immutability of the message, and MUST return an instance that has the updated query string arguments.
withUploadedFiles(array $uploadedFiles): static
Create a new instance with the specified uploaded files.
This method MUST be implemented in such a way as to retain the immutability of the message, and MUST return an instance that has the updated body parameters.
getMethod(): string
Retrieves the HTTP method of the request.
getRequestTarget(): string
Retrieves the message's request target.
Retrieves the message's request-target either as it will appear (for clients), as it appeared at request (for servers), or as it was specified for the instance (see withRequestTarget()).
In most cases, this will be the origin-form of the composed URI, unless a value was provided to the concrete implementation (see withRequestTarget() below).
If no URI is available, and no request-target has been specifically provided, this method MUST return the string "/".
getUri(): UriInterface
Retrieves the URI instance.
This method MUST return a UriInterface instance.
withMethod(string $method): static
Return an instance with the provided HTTP method.
While HTTP method names are typically all uppercase characters, HTTP method names are case-sensitive and thus implementations SHOULD NOT modify the given string.
This method MUST be implemented in such a way as to retain the immutability of the message, and MUST return an instance that has the changed request method.
withRequestTarget(string $requestTarget): static
Return an instance with the specific request-target.
If the request needs a non-origin-form request-target — e.g., for specifying an absolute-form, authority-form, or asterisk-form — this method may be used to create an instance with the specified request-target, verbatim.
This method MUST be implemented in such a way as to retain the immutability of the message, and MUST return an instance that has the changed request target.
withUri(UriInterface $uri[, bool $preserveHost = false]): static
Returns an instance with the provided URI.
This method MUST update the Host header of the returned request by default if the URI contains a host component. If the URI does not contain a host component, any pre-existing Host header MUST be carried over to the returned request.
You can opt-in to preserving the original state of the Host header by
setting $preserveHost
to true
. When $preserveHost
is set to
true
, this method interacts with the Host header in the following ways:
This method MUST be implemented in such a way as to retain the immutability of the message, and MUST return an instance that has the new UriInterface instance.
getBody(): StreamInterface
Gets the body of the message.
getHeader(string $name): string[]
Retrieves a message header value by the given case-insensitive name.
This method returns an array of all the header values of the given case-insensitive header name.
If the header does not appear in the message, this method MUST return an empty array.
getHeaderLine(string $name): string
Retrieves a comma-separated string of the values for a single header.
This method returns all of the header values of the given case-insensitive header name as a string concatenated together using a comma.
If the header does not appear in the message, this method MUST return an empty string.
getHeaders(): string[][]
Retrieves all message header values.
The keys represent the header name as it will be sent over the wire, and each value is an array of strings associated with the header.
// Represent the headers as a string
foreach ($message->getHeaders() as $name => $values) {
echo $name . ": " . implode(", ", $values);
}
// Emit headers iteratively:
foreach ($message->getHeaders() as $name => $values) {
foreach ($values as $value) {
header(sprintf('%s: %s', $name, $value), false);
}
}
While header names are not case-sensitive, getHeaders() will preserve the exact case in which headers were originally specified.
getProtocolVersion(): string
Retrieves the HTTP protocol version as a string.
The string MUST contain only the HTTP version number (e.g., "1.1", "1.0").
hasHeader(string $name): bool
Checks if a header exists by the given case-insensitive name.
withAddedHeader(string $name, string|string[] $value): static
Return an instance with the specified header appended with the given value.
Existing values for the specified header will be maintained. The new value(s) will be appended to the existing list. If the header did not exist previously, it will be added.
This method MUST be implemented in such a way as to retain the immutability of the message, and MUST return an instance that has the new header and/or value.
withBody(StreamInterface $body): static
Return an instance with the specified message body.
The body MUST be a StreamInterface object.
This method MUST be implemented in such a way as to retain the immutability of the message, and MUST return a new instance that has the new body stream.
withHeader(string $name, string|string[] $value): static
Return an instance with the provided value replacing the specified header.
While header names are case-insensitive, the casing of the header will be preserved by this function, and returned from getHeaders().
This method MUST be implemented in such a way as to retain the immutability of the message, and MUST return an instance that has the new and/or updated header and value.
withoutHeader(string $name): static
Return an instance without the specified header.
Header resolution MUST be done without case-sensitivity.
This method MUST be implemented in such a way as to retain the immutability of the message, and MUST return an instance that removes the named header.
withProtocolVersion(string $version): static
Return an instance with the specified HTTP protocol version.
The version string MUST contain only the HTTP version number (e.g., "1.1", "1.0").
This method MUST be implemented in such a way as to retain the immutability of the message, and MUST return an instance that has the new protocol version.
Describes a data stream.
__construct(mixed $resource = null[, array $options = array()])
This constructor accepts an associative array of options.
__toString(): string
Reads all data from the stream into a string, from the beginning to end.
Warning: This could attempt to load a large amount of data into memory.
close()
Closes the stream and any underlying resources.
detach(): resource|null
Separates any underlying resources from the stream.
After the stream has been detached, the stream is in an unusable state.
eof(): bool
Returns true if the stream is at the end of the stream.
getContents(): string
Returns the remaining contents in a string
getMetadata(string|null $key = null): array|mixed|null
Get stream metadata as an associative array or retrieve a specific key.
The keys returned are identical to the keys returned from PHP's stream_get_meta_data() function.
getSize(): int|null
Get the size of the stream if known.
isReadable(): bool
Returns whether or not the stream is readable.
isSeekable(): bool
Returns whether or not the stream is seekable.
isWritable(): bool
Returns whether or not the stream is writable.
read(int $length): string
Read data from the stream.
rewind()
Seek to the beginning of the stream.
If the stream is not seekable, this method will raise an exception; otherwise, it will perform a seek(0).
seek(int $offset[, int $whence = SEEK_SET])
Seek to a position in the stream.
fseek()
.
SEEK_SET: Set position equal to offset bytes
SEEK_CUR: Set position to current location plus offset
SEEK_END: Set position to end-of-stream plus offset.tell(): int
Returns the current position of the file read/write pointer
write(string $string): int
Write data to the stream.
Value object representing a file uploaded through an HTTP request.
Instances of this interface are considered immutable; all methods that might change state are implemented such that they retain the internal state of the current instance and return an instance that contains the changed state.
__construct(mixed …$values = array())
Constructor
construct(array $fileInfo) construct($streamOrFile, $size = null, $error = UPLOAD_ERR_OK, $clientFilename = null, $clientMediaType = null, $clientFullPath = null)
getClientFilename(): string|null
Retrieve the filename sent by the client.
Do not trust the value returned by this method. A client could send a malicious filename with the intention to corrupt or hack your application.
getClientFullPath(): string|null
Retrieve the full_path sent by the client.
full_path value is new as of PHP 8.1 and passed by client when uploading a directory
Do not trust the value returned by this method. A client could send a malicious filename with the intention to corrupt or hack your application.
null
if none was provided.getClientMediaType(): string|null
Retrieve the media type sent by the client.
Do not trust the value returned by this method. A client could send a malicious media type with the intention to corrupt or hack your application.
getError(): int
Retrieve the error associated with the uploaded file.
Returns one of PHP's UPLOAD_ERR_XXX constants.
If the file was uploaded successfully, will return
UPLOAD_ERR_OK
.
getErrorMessage(): string
Get uploaded file's error message
If the file was uploaded successfully, will return ''
getSize(): int|null
Retrieve the file size.
Implementations SHOULD return the value stored in the "size" key of the file in the $_FILES array if available, as PHP calculates this based on the actual size transmitted.
getStream(): Psr\Http\Message\StreamInterface
Retrieve a stream representing the uploaded file.
If the moveTo() method has been called previously, this method will raise an exception.
moveTo(string $targetPath)
Move the uploaded file to a new location.
Use this method as an alternative to move_uploaded_file(). This method is guaranteed to work in both SAPI and non-SAPI environments.
$targetPath may be an absolute path, or a relative path. If it is a relative path, resolution will be the same as used by PHP's rename() function.
The original file or stream will be removed on completion.
If this method is called more than once, any subsequent calls will raise an exception.
When used in an SAPI environment where $_FILES is populated, when writing files via moveTo(), is_uploaded_file() and move_uploaded_file() SHOULD be used to ensure permissions and upload status are verified correctly.
If you wish to move to a stream, use getStream(), as SAPI operations cannot guarantee writing to stream destinations.
Value object representing a URI.
Represent a URI according to RFC 3986 and provide methods for most common operations.
Instances of this interface are considered immutable; all methods that might change state are implemented such that they retain the internal state of the current instance and return an instance that contains the changed state.
__construct(string|null $uri = null)
Constructor
__toString(): string
Return stringified value
static fromGlobals(): bdk\HttpMessage\Uri
Get a Uri populated with values from $_SERVER.
\bdk\HttpMessage\Utiity\Uri::fromGlobals
insteadgetAuthority(): string
Retrieve the authority component of the URI.
If the port component is not set or is the standard port for the current scheme, it will not be included
getFragment(): string
Retrieve the fragment component of the URI.
The leading "#" character is not part of the fragment and MUST NOT be added.
The value returned will be percent-encoded, but will not double-encode any characters. see RFC 3986, Sections 2 and 3.5.
getHost(): string
Retrieve the host component of the URI.
The value returned will be normalized to lowercase, per RFC 3986 Section 3.2.2.
getPath(): string
Retrieve the path component of the URI.
The path can either be empty or absolute (starting with a slash) rootless (not starting with a slash).
Normally, the empty path "" and absolute path "/" are considered equal as defined in RFC 7230 Section 2.7.3. But this method does automatically do this normalization because in contexts with a trimmed base path, e.g. the front controller, this difference becomes significant. It's the task of the user to handle both "" and "/".
The value returned will be percent-encoded, but will not double-encode any characters. see RFC 3986, Sections 2 and 3.3.
As an example, if the value should include a slash ("/") not intended as delimiter between path segments, that value will be passed in encoded form (e.g., "%2F") to the instance.
getPort(): null|int
Retrieve the port component of the URI.
If the port is the standard port used with the current scheme, null will be returned.
If no port is present, and no scheme is present, null will be returned
If no port is present, but a scheme is present, null will be returned.
getQuery(): string
Retrieve the query string of the URI.
The leading "?" character is not part of the query and will not be included.
The value returned will be percent-encoded, but will not double-encode any characters. see RFC 3986, Sections 2 and 3.4.
As an example, if a value in a key/value pair of the query string should include an ampersand ("&") not intended as a delimiter between values, that value MUST be passed in encoded form (e.g., "%26") to the instance.
getScheme(): string
Retrieve the scheme component of the URI.
getUserInfo(): string
Retrieve the user information component of the URI.
If a user is present in the URI, this will return that value; additionally, if the password is also present, it will be appended to the user value, with a colon (":") separating the values.
The trailing "@" character is not part of the user information and will not be included
withFragment(string $fragment): static
Return an instance with the specified URI fragment.
Users can provide both encoded and decoded fragment characters.
An empty fragment value is equivalent to removing the fragment.
withHost(string $host): static
Return an instance with the specified host.
An empty host value is equivalent to removing the host.
withPath(string $path): static
Return an instance with the specified path.
The path can either be empty absolute (starting with a slash) rootless (not starting with a slash).
If an HTTP path is intended to be host-relative rather than path-relative then it must begin with a slash ("/"). HTTP paths not starting with a slash are assumed to be relative to some base path known to the application or consumer.
Users can provide both encoded and decoded path characters.
withPort(null|int $port): static
Return an instance with the specified port.
A null value provided for the port is equivalent to removing the port information.
withQuery(string $query): static
Return an instance with the specified query string.
Users can provide both encoded and decoded query characters.
An empty query string value is equivalent to removing the query string.
withScheme(string $scheme): static
Return an instance with the specified scheme.
An empty scheme is equivalent to removing the scheme.
withUserInfo(string $user[, null|string $password = null]): static
Return an instance with the specified user information.
Password is optional, but the user information MUST include the user; an empty string for the user is equivalent to removing user information.
Define common mime types
Factories for creating ServerRequest & Response from HttpFoundation objects
static createRequest(Symfony\Component\HttpFoundation\Request $request): bdk\HttpMessage\ServerRequestExtended
Create a Psr7 request object from HttpFoundation request
static createResponse(Symfony\Component\HttpFoundation\Response $response): bdk\HttpMessage\Response
Create Response from HttpFoundationResponse
PHP's parse_str()
, but does not convert dots and spaces to '_' by default
PHP's maintains a side-effect of the long-removed register_globals directive that affects $_POST
and $_GET
Spaces and '.'s are converted to '_' for top level keys.
$input = 'foo_bar=baz+1&foo+bar=baz+2&foo%2Bbar=baz+3&foo.bar=baz+4';
parse_str($input, $vals);
var_dump($vals);
$vals = \bdk\HttpMessage\Utility\ParseStr::parse($input);
var_dump($vals);
Output:
array(
'foo_bar' => 'baz 4',
'foo+bar' => 'baz 3',
)
array(
'foo_bar' => 'baz 1',
'foo bar' => 'baz 2',
'foo+bar' => 'baz 3',
'foo.bar' => 'baz 4',
)
static parse(string|null $str[, array $opts = array()]): array
like PHP's parse_str()
Key difference: by default this does not convert root key dots and spaces to '_'
static setOpts(array|string $mixed[, mixed $val = null])
Set default parseStr option(s)
parseStrOpts('convDot', true)
parseStrOpts(array('convDot' => true, 'convSpace' => true))
Response Utilities
static codePhrase(int|string $code): string
Get the standard "phrase" associated with the status code
static emit(Psr\Http\Message\ResponseInterface $response)
Output response headers and body
Build ServerRequest from globals ($_SERVER
, $_COOKIE
, $_POST
, $_FILES
)
static fromGlobals(array $parseStrOpts = array()): bdk\HttpMessage\ServerRequestExtended
Instantiate ServerRequest instance from superglobals
Stream Utilities
static getContents(Psr\Http\Message\StreamInterface $stream): string
Get stream contents without affecting pointer
Uri Utilities
static fromGlobals(): bdk\HttpMessage\Uri
Get a Uri populated with values from $_SERVER
.
static fromParsed(array $parsed): bdk\HttpMessage\Uri
Get a Uri populated with component values
Username & password accepted in multiple ways (highest precedence first):
parse_url()
)static isCrossOrigin(Psr\Http\Message\UriInterface $uri1, Psr\Http\Message\UriInterface $uri2): bool
Determines if two Uri's should be considered cross-origin
static parseUrl(string|Psr\Http\Message\UriInterface $url): array<string,int|string>|false
Parse URL (multi-byte safe)
static resolve(Psr\Http\Message\UriInterface $base, Psr\Http\Message\UriInterface $rel): Psr\Http\Message\UriInterface
Converts the relative URI into a new URI that is resolved against the base URI.