Response
in package
implements
ResponseInterface
uses
MessageTrait
Responses contain the response text, status and headers of a HTTP response.
There are external packages such as fig/http-message-util
that provide HTTP
status code constants. These can be used with any method that accepts or
returns a status code integer. Keep in mind that these constants might
include status codes that are now allowed which will throw an
\InvalidArgumentException
.
Table of Contents
Interfaces
- ResponseInterface
- Representation of an outgoing, server-side response.
Constants
- STATUS_CODE_MAX = 599
- STATUS_CODE_MIN = 100
Properties
- $_cacheDirectives : array<string, mixed>
- Holds all the cache directives that will be converted into headers when sending the request
- $_charset : string
- The charset the response body is encoded with
- $_cookies : CookieCollection
- Collection of cookies to send to the client
- $_file : SplFileInfo|null
- File object for file to be read out as response
- $_fileRange : array<string|int, int>
- File range. Used for requesting ranges of files.
- $_mimeTypes : array<string, mixed>
- Holds type key to mime type mappings for known mime types.
- $_reasonPhrase : string
- Reason Phrase
- $_status : int
- Status code to send to the client
- $_statusCodes : array<int, string>
- Allowed HTTP status codes and their default description.
- $_streamMode : string
- Stream mode options.
- $_streamTarget : resource|string
- Stream target or resource object.
- $headerNames : array<string|int, mixed>
- Map of normalized header name to original name used to register header.
- $headers : array<string|int, mixed>
- List of all registered headers, as key => array of values.
- $protocol : string
- $stream : StreamInterface
Methods
- __construct() : mixed
- Constructor
- __debugInfo() : array<string, mixed>
- Returns an array that can be used to describe the internal state of this object.
- __toString() : string
- String conversion. Fetches the response body as a string.
- checkNotModified() : bool
- Checks whether a response has not been modified according to the 'If-None-Match' (Etags) and 'If-Modified-Since' (last modification date) request headers. If the response is detected to be not modified, it is marked as so accordingly so the client can be informed of that.
- compress() : bool
- Sets the correct output buffering handler to send a compressed response. Responses will be compressed with zlib, if the extension is available.
- cors() : CorsBuilder
- Get a CorsBuilder instance for defining CORS headers.
- getBody() : StreamInterface
- Gets the body of the message.
- getCharset() : string
- Returns the current charset.
- getCookie() : array<string|int, mixed>|null
- Read a single cookie from the response.
- getCookieCollection() : CookieCollection
- Get the CookieCollection from the response
- getCookies() : array<string, array<string|int, mixed>>
- Get all cookies in the response.
- getFile() : SplFileInfo|null
- Get the current file if one exists.
- getHeader() : array<string|int, string>
- Retrieves a message header value by the given case-insensitive name.
- getHeaderLine() : string
- Retrieves a comma-separated string of the values for a single header.
- getHeaders() : array<string|int, mixed>
- Retrieves all message headers.
- getMimeType() : array<string|int, mixed>|string|false
- Returns the mime type definition for an alias
- getProtocolVersion() : string
- Retrieves the HTTP protocol version as a string.
- getReasonPhrase() : string
- Gets the response reason phrase associated with the status code.
- getStatusCode() : int
- Gets the response status code.
- getType() : string
- Returns the current content type.
- hasHeader() : bool
- Checks if a header exists by the given case-insensitive name.
- isNotModified() : bool
- Checks whether a response has not been modified according to the 'If-None-Match' (Etags) and 'If-Modified-Since' (last modification date) request headers.
- mapType() : array<string|int, mixed>|string|null
- Maps a content-type back to an alias
- notModified() : void
- Sets the response as Not Modified by removing any body contents setting the status code to "304 Not Modified" and removing all conflicting headers
- outputCompressed() : bool
- Returns whether the resulting output will be compressed by PHP
- setTypeMap() : void
- Sets a content type definition into the map.
- withAddedHeader() : static
- Return an instance with the specified header appended with the given value.
- withAddedLink() : static
- Create a new response with the Link header set.
- withBody() : static
- Return an instance with the specified message body.
- withCache() : static
- Create a new instance with the headers to enable client caching.
- withCharset() : static
- Get a new instance with an updated charset.
- withCookie() : static
- Create a new response with a cookie set.
- withCookieCollection() : static
- Get a new instance with provided cookie collection.
- withDisabledCache() : static
- Create a new instance with headers to instruct the client to not cache the response
- withDownload() : static
- Create a new instance with the Content-Disposition header set.
- withEtag() : static
- Create a new instance with the Etag header set.
- withExpiredCookie() : static
- Create a new response with an expired cookie set.
- withExpires() : static
- Create a new instance with the Expires header set.
- withFile() : static
- Create a new instance that is based on a file.
- withHeader() : static
- Return an instance with the provided header, replacing any existing values of any headers with the same case-insensitive name.
- withLength() : static
- Create a new response with the Content-Length header set.
- withLocation() : static
- Return an instance with an updated location header.
- withMaxAge() : static
- Create an instance with Cache-Control max-age directive set.
- withModified() : static
- Create a new instance with the Last-Modified header set.
- withMustRevalidate() : static
- Create an instance with Cache-Control must-revalidate directive set.
- withNotModified() : static
- Create a new instance as 'not modified'
- withoutHeader() : static
- Return an instance without the specified header.
- withProtocolVersion() : static
- Return an instance with the specified HTTP protocol version.
- withSharable() : static
- Create a new instace with the public/private Cache-Control directive set.
- withSharedMaxAge() : static
- Create a new instance with the Cache-Control s-maxage directive.
- withStatus() : static
- Return an instance with the specified status code and, optionally, reason phrase.
- withStringBody() : static
- Convenience method to set a string into the response body
- withType() : static
- Get an updated response with the content type set.
- withVary() : static
- Create a new instance with the Vary header set.
- _clearHeader() : void
- Clear header
- _createStream() : void
- Creates the stream object.
- _fileRange() : void
- Apply a file range to a file and set the end offset.
- _getUTCDate() : DateTimeInterface
- Returns a DateTime object initialized at the $time param and using UTC as timezone
- _setCacheControl() : void
- Helper method to generate a valid Cache-Control header from the options set in other methods
- _setContentType() : void
- Formats the Content-Type header based on the configured contentType and charset the charset will only be set in the header if the response is of type text/*
- _setHeader() : void
- Sets a header.
- _setStatus() : void
- Modifier for response status
- resolveType() : string
- Translate and validate content-types.
- validateFile() : SplFileInfo
- Validate a file path is a valid response body.
- assertHeader() : void
- Ensure header name and values are valid.
- filterHeaderValue() : array<int, string>
- getStream() : StreamInterface
- setHeaders() : void
- Filter a set of headers to ensure they are in the correct internal format.
- validateProtocolVersion() : void
- Validate the HTTP protocol version
Constants
STATUS_CODE_MAX
public
int
STATUS_CODE_MAX
= 599
STATUS_CODE_MIN
public
int
STATUS_CODE_MIN
= 100
Properties
$_cacheDirectives
Holds all the cache directives that will be converted into headers when sending the request
protected
array<string, mixed>
$_cacheDirectives
= []
$_charset
The charset the response body is encoded with
protected
string
$_charset
= 'UTF-8'
$_cookies
Collection of cookies to send to the client
protected
CookieCollection
$_cookies
$_file
File object for file to be read out as response
protected
SplFileInfo|null
$_file
$_fileRange
File range. Used for requesting ranges of files.
protected
array<string|int, int>
$_fileRange
= []
$_mimeTypes
Holds type key to mime type mappings for known mime types.
protected
array<string, mixed>
$_mimeTypes
= ['html' => ['text/html', '*/*'], 'json' => 'application/json', 'xml' => ['application/xml', 'text/xml'], 'xhtml' => ['application/xhtml+xml', 'application/xhtml', 'text/xhtml'], 'webp' => 'image/webp', 'rss' => 'application/rss+xml', 'ai' => 'application/postscript', 'bcpio' => 'application/x-bcpio', 'bin' => 'application/octet-stream', 'ccad' => 'application/clariscad', 'cdf' => 'application/x-netcdf', 'class' => 'application/octet-stream', 'cpio' => 'application/x-cpio', 'cpt' => 'application/mac-compactpro', 'csh' => 'application/x-csh', 'csv' => ['text/csv', 'application/vnd.ms-excel'], 'dcr' => 'application/x-director', 'dir' => 'application/x-director', 'dms' => 'application/octet-stream', 'doc' => 'application/msword', 'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'drw' => 'application/drafting', 'dvi' => 'application/x-dvi', 'dwg' => 'application/acad', 'dxf' => 'application/dxf', 'dxr' => 'application/x-director', 'eot' => 'application/vnd.ms-fontobject', 'eps' => 'application/postscript', 'exe' => 'application/octet-stream', 'ez' => 'application/andrew-inset', 'flv' => 'video/x-flv', 'gtar' => 'application/x-gtar', 'gz' => 'application/x-gzip', 'bz2' => 'application/x-bzip', '7z' => 'application/x-7z-compressed', 'hal' => ['application/hal+xml', 'application/vnd.hal+xml'], 'haljson' => ['application/hal+json', 'application/vnd.hal+json'], 'halxml' => ['application/hal+xml', 'application/vnd.hal+xml'], 'hdf' => 'application/x-hdf', 'hqx' => 'application/mac-binhex40', 'ico' => 'image/x-icon', 'ips' => 'application/x-ipscript', 'ipx' => 'application/x-ipix', 'js' => 'application/javascript', 'jsonapi' => 'application/vnd.api+json', 'latex' => 'application/x-latex', 'jsonld' => 'application/ld+json', 'kml' => 'application/vnd.google-earth.kml+xml', 'kmz' => 'application/vnd.google-earth.kmz', 'lha' => 'application/octet-stream', 'lsp' => 'application/x-lisp', 'lzh' => 'application/octet-stream', 'man' => 'application/x-troff-man', 'me' => 'application/x-troff-me', 'mif' => 'application/vnd.mif', 'ms' => 'application/x-troff-ms', 'nc' => 'application/x-netcdf', 'oda' => 'application/oda', 'otf' => 'font/otf', 'pdf' => 'application/pdf', 'pgn' => 'application/x-chess-pgn', 'pot' => 'application/vnd.ms-powerpoint', 'pps' => 'application/vnd.ms-powerpoint', 'ppt' => 'application/vnd.ms-powerpoint', 'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation', 'ppz' => 'application/vnd.ms-powerpoint', 'pre' => 'application/x-freelance', 'prt' => 'application/pro_eng', 'ps' => 'application/postscript', 'roff' => 'application/x-troff', 'scm' => 'application/x-lotusscreencam', 'set' => 'application/set', 'sh' => 'application/x-sh', 'shar' => 'application/x-shar', 'sit' => 'application/x-stuffit', 'skd' => 'application/x-koan', 'skm' => 'application/x-koan', 'skp' => 'application/x-koan', 'skt' => 'application/x-koan', 'smi' => 'application/smil', 'smil' => 'application/smil', 'sol' => 'application/solids', 'spl' => 'application/x-futuresplash', 'src' => 'application/x-wais-source', 'step' => 'application/STEP', 'stl' => 'application/SLA', 'stp' => 'application/STEP', 'sv4cpio' => 'application/x-sv4cpio', 'sv4crc' => 'application/x-sv4crc', 'svg' => 'image/svg+xml', 'svgz' => 'image/svg+xml', 'swf' => 'application/x-shockwave-flash', 't' => 'application/x-troff', 'tar' => 'application/x-tar', 'tcl' => 'application/x-tcl', 'tex' => 'application/x-tex', 'texi' => 'application/x-texinfo', 'texinfo' => 'application/x-texinfo', 'tr' => 'application/x-troff', 'tsp' => 'application/dsptype', 'ttc' => 'font/ttf', 'ttf' => 'font/ttf', 'unv' => 'application/i-deas', 'ustar' => 'application/x-ustar', 'vcd' => 'application/x-cdlink', 'vda' => 'application/vda', 'xlc' => 'application/vnd.ms-excel', 'xll' => 'application/vnd.ms-excel', 'xlm' => 'application/vnd.ms-excel', 'xls' => 'application/vnd.ms-excel', 'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'xlw' => 'application/vnd.ms-excel', 'zip' => 'application/zip', 'aif' => 'audio/x-aiff', 'aifc' => 'audio/x-aiff', 'aiff' => 'audio/x-aiff', 'au' => 'audio/basic', 'kar' => 'audio/midi', 'mid' => 'audio/midi', 'midi' => 'audio/midi', 'mp2' => 'audio/mpeg', 'mp3' => 'audio/mpeg', 'mpga' => 'audio/mpeg', 'ogg' => 'audio/ogg', 'oga' => 'audio/ogg', 'spx' => 'audio/ogg', 'ra' => 'audio/x-realaudio', 'ram' => 'audio/x-pn-realaudio', 'rm' => 'audio/x-pn-realaudio', 'rpm' => 'audio/x-pn-realaudio-plugin', 'snd' => 'audio/basic', 'tsi' => 'audio/TSP-audio', 'wav' => 'audio/x-wav', 'aac' => 'audio/aac', 'asc' => 'text/plain', 'c' => 'text/plain', 'cc' => 'text/plain', 'css' => 'text/css', 'etx' => 'text/x-setext', 'f' => 'text/plain', 'f90' => 'text/plain', 'h' => 'text/plain', 'hh' => 'text/plain', 'htm' => ['text/html', '*/*'], 'ics' => 'text/calendar', 'm' => 'text/plain', 'rtf' => 'text/rtf', 'rtx' => 'text/richtext', 'sgm' => 'text/sgml', 'sgml' => 'text/sgml', 'tsv' => 'text/tab-separated-values', 'tpl' => 'text/template', 'txt' => 'text/plain', 'text' => 'text/plain', 'avi' => 'video/x-msvideo', 'fli' => 'video/x-fli', 'mov' => 'video/quicktime', 'movie' => 'video/x-sgi-movie', 'mpe' => 'video/mpeg', 'mpeg' => 'video/mpeg', 'mpg' => 'video/mpeg', 'qt' => 'video/quicktime', 'viv' => 'video/vnd.vivo', 'vivo' => 'video/vnd.vivo', 'ogv' => 'video/ogg', 'webm' => 'video/webm', 'mp4' => 'video/mp4', 'm4v' => 'video/mp4', 'f4v' => 'video/mp4', 'f4p' => 'video/mp4', 'm4a' => 'audio/mp4', 'f4a' => 'audio/mp4', 'f4b' => 'audio/mp4', 'gif' => 'image/gif', 'ief' => 'image/ief', 'jpg' => 'image/jpeg', 'jpeg' => 'image/jpeg', 'jpe' => 'image/jpeg', 'pbm' => 'image/x-portable-bitmap', 'pgm' => 'image/x-portable-graymap', 'png' => 'image/png', 'pnm' => 'image/x-portable-anymap', 'ppm' => 'image/x-portable-pixmap', 'ras' => 'image/cmu-raster', 'rgb' => 'image/x-rgb', 'tif' => 'image/tiff', 'tiff' => 'image/tiff', 'xbm' => 'image/x-xbitmap', 'xpm' => 'image/x-xpixmap', 'xwd' => 'image/x-xwindowdump', 'psd' => ['application/photoshop', 'application/psd', 'image/psd', 'image/x-photoshop', 'image/photoshop', 'zz-application/zz-winassoc-psd'], 'ice' => 'x-conference/x-cooltalk', 'iges' => 'model/iges', 'igs' => 'model/iges', 'mesh' => 'model/mesh', 'msh' => 'model/mesh', 'silo' => 'model/mesh', 'vrml' => 'model/vrml', 'wrl' => 'model/vrml', 'mime' => 'www/mime', 'pdb' => 'chemical/x-pdb', 'xyz' => 'chemical/x-pdb', 'javascript' => 'application/javascript', 'form' => 'application/x-www-form-urlencoded', 'file' => 'multipart/form-data', 'xhtml-mobile' => 'application/vnd.wap.xhtml+xml', 'atom' => 'application/atom+xml', 'amf' => 'application/x-amf', 'wap' => ['text/vnd.wap.wml', 'text/vnd.wap.wmlscript', 'image/vnd.wap.wbmp'], 'wml' => 'text/vnd.wap.wml', 'wmlscript' => 'text/vnd.wap.wmlscript', 'wbmp' => 'image/vnd.wap.wbmp', 'woff' => 'application/x-font-woff', 'appcache' => 'text/cache-manifest', 'manifest' => 'text/cache-manifest', 'htc' => 'text/x-component', 'rdf' => 'application/xml', 'crx' => 'application/x-chrome-extension', 'oex' => 'application/x-opera-extension', 'xpi' => 'application/x-xpinstall', 'safariextz' => 'application/octet-stream', 'webapp' => 'application/x-web-app-manifest+json', 'vcf' => 'text/x-vcard', 'vtt' => 'text/vtt', 'mkv' => 'video/x-matroska', 'pkpass' => 'application/vnd.apple.pkpass', 'ajax' => 'text/html', 'bmp' => 'image/bmp']
$_reasonPhrase
Reason Phrase
protected
string
$_reasonPhrase
= 'OK'
$_status
Status code to send to the client
protected
int
$_status
= 200
$_statusCodes
Allowed HTTP status codes and their default description.
protected
array<int, string>
$_statusCodes
= [100 => 'Continue', 101 => 'Switching Protocols', 102 => 'Processing', 200 => 'OK', 201 => 'Created', 202 => 'Accepted', 203 => 'Non-Authoritative Information', 204 => 'No Content', 205 => 'Reset Content', 206 => 'Partial Content', 207 => 'Multi-status', 208 => 'Already Reported', 226 => 'IM used', 300 => 'Multiple Choices', 301 => 'Moved Permanently', 302 => 'Found', 303 => 'See Other', 304 => 'Not Modified', 305 => 'Use Proxy', 306 => '(Unused)', 307 => 'Temporary Redirect', 308 => 'Permanent Redirect', 400 => 'Bad Request', 401 => 'Unauthorized', 402 => 'Payment Required', 403 => 'Forbidden', 404 => 'Not Found', 405 => 'Method Not Allowed', 406 => 'Not Acceptable', 407 => 'Proxy Authentication Required', 408 => 'Request Timeout', 409 => 'Conflict', 410 => 'Gone', 411 => 'Length Required', 412 => 'Precondition Failed', 413 => 'Request Entity Too Large', 414 => 'Request-URI Too Large', 415 => 'Unsupported Media Type', 416 => 'Requested range not satisfiable', 417 => 'Expectation Failed', 418 => 'I\'m a teapot', 421 => 'Misdirected Request', 422 => 'Unprocessable Entity', 423 => 'Locked', 424 => 'Failed Dependency', 425 => 'Unordered Collection', 426 => 'Upgrade Required', 428 => 'Precondition Required', 429 => 'Too Many Requests', 431 => 'Request Header Fields Too Large', 444 => 'Connection Closed Without Response', 451 => 'Unavailable For Legal Reasons', 499 => 'Client Closed Request', 500 => 'Internal Server Error', 501 => 'Not Implemented', 502 => 'Bad Gateway', 503 => 'Service Unavailable', 504 => 'Gateway Timeout', 505 => 'Unsupported Version', 506 => 'Variant Also Negotiates', 507 => 'Insufficient Storage', 508 => 'Loop Detected', 510 => 'Not Extended', 511 => 'Network Authentication Required', 599 => 'Network Connect Timeout Error']
$_streamMode
Stream mode options.
protected
string
$_streamMode
= 'wb+'
$_streamTarget
Stream target or resource object.
protected
resource|string
$_streamTarget
= 'php://memory'
$headerNames
Map of normalized header name to original name used to register header.
protected
array<string|int, mixed>
$headerNames
= []
Tags
$headers
List of all registered headers, as key => array of values.
protected
array<string|int, mixed>
$headers
= []
Tags
$protocol
private
string
$protocol
= '1.1'
$stream
private
StreamInterface
$stream
Methods
__construct()
Constructor
public
__construct([array<string, mixed> $options = [] ]) : mixed
Parameters
- $options : array<string, mixed> = []
-
list of parameters to setup the response. Possible values are:
- body: the response text that should be sent to the client
- status: the HTTP status code to respond with
- type: a complete mime-type string or an extension mapped in this class
- charset: the charset for the response body
Tags
__debugInfo()
Returns an array that can be used to describe the internal state of this object.
public
__debugInfo() : array<string, mixed>
Return values
array<string, mixed>__toString()
String conversion. Fetches the response body as a string.
public
__toString() : string
Does not send headers. If body is a callable, a blank string is returned.
Return values
stringcheckNotModified()
Checks whether a response has not been modified according to the 'If-None-Match' (Etags) and 'If-Modified-Since' (last modification date) request headers. If the response is detected to be not modified, it is marked as so accordingly so the client can be informed of that.
public
checkNotModified(ServerRequest $request) : bool
Use isNotModified()
and withNotModified()
instead.
In order to mark a response as not modified, you need to set at least the Last-Modified etag response header before calling this method. Otherwise a comparison will not be possible.
Warning This method mutates the response in-place and should be avoided.
Parameters
- $request : ServerRequest
-
Request object
Return values
bool —Whether the response was marked as not modified or not.
compress()
Sets the correct output buffering handler to send a compressed response. Responses will be compressed with zlib, if the extension is available.
public
compress() : bool
Return values
bool —false if client does not accept compressed responses or no handler is available, true otherwise
cors()
Get a CorsBuilder instance for defining CORS headers.
public
cors(ServerRequest $request) : CorsBuilder
Parameters
- $request : ServerRequest
-
Request object
Return values
CorsBuilder —A builder object the provides a fluent interface for defining additional CORS headers.
getBody()
Gets the body of the message.
public
getBody() : StreamInterface
Return values
StreamInterface —Returns the body as a stream.
getCharset()
Returns the current charset.
public
getCharset() : string
Return values
stringgetCookie()
Read a single cookie from the response.
public
getCookie(string $name) : array<string|int, mixed>|null
This method provides read access to pending cookies. It will
not read the Set-Cookie
header if set.
Parameters
- $name : string
-
The cookie name you want to read.
Return values
array<string|int, mixed>|null —Either the cookie data or null
getCookieCollection()
Get the CookieCollection from the response
public
getCookieCollection() : CookieCollection
Return values
CookieCollectiongetCookies()
Get all cookies in the response.
public
getCookies() : array<string, array<string|int, mixed>>
Returns an associative array of cookie name => cookie data.
Return values
array<string, array<string|int, mixed>>getFile()
Get the current file if one exists.
public
getFile() : SplFileInfo|null
Return values
SplFileInfo|null —The file to use in the response or null
getHeader()
Retrieves a message header value by the given case-insensitive name.
public
getHeader(string $header) : array<string|int, string>
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.
Parameters
- $header : string
-
Case-insensitive header field name.
Return values
array<string|int, string> —An array of string values as provided for the given header. If the header does not appear in the message, this method MUST return an empty array.
getHeaderLine()
Retrieves a comma-separated string of the values for a single header.
public
getHeaderLine(string $name) : string
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 MUST return an empty string.
Parameters
- $name : string
-
Case-insensitive header field name.
Return values
string —A string of values as provided for the given header concatenated together using a comma. If the header does not appear in the message, this method MUST return an empty string.
getHeaders()
Retrieves all message headers.
public
getHeaders() : array<string|int, mixed>
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);
}
}
Tags
Return values
array<string|int, mixed> —Returns an associative array of the message's headers. Each key MUST be a header name, and each value MUST be an array of strings.
getMimeType()
Returns the mime type definition for an alias
public
getMimeType(string $alias) : array<string|int, mixed>|string|false
e.g getMimeType('pdf'); // returns 'application/pdf'
Parameters
- $alias : string
-
the content type alias to map
Return values
array<string|int, mixed>|string|false —String mapped mime type or false if $alias is not mapped
getProtocolVersion()
Retrieves the HTTP protocol version as a string.
public
getProtocolVersion() : string
The string MUST contain only the HTTP version number (e.g., "1.1", "1.0").
Return values
string —HTTP protocol version.
getReasonPhrase()
Gets the response reason phrase associated with the status code.
public
getReasonPhrase() : string
Because a reason phrase is not a required element in a response status line, the reason phrase value MAY be null. Implementations MAY choose to return the default RFC 7231 recommended reason phrase (or those listed in the IANA HTTP Status Code Registry) for the response's status code.
Tags
Return values
string —Reason phrase; must return an empty string if none present.
getStatusCode()
Gets the response status code.
public
getStatusCode() : int
The status code is a 3-digit integer result code of the server's attempt to understand and satisfy the request.
Return values
int —Status code.
getType()
Returns the current content type.
public
getType() : string
Return values
stringhasHeader()
Checks if a header exists by the given case-insensitive name.
public
hasHeader(string $header) : bool
Parameters
- $header : string
-
Case-insensitive header name.
Return values
bool —Returns true if any header names match the given header name using a case-insensitive string comparison. Returns false if no matching header name is found in the message.
isNotModified()
Checks whether a response has not been modified according to the 'If-None-Match' (Etags) and 'If-Modified-Since' (last modification date) request headers.
public
isNotModified(ServerRequest $request) : bool
In order to interact with this method you must mark responses as not modified.
You need to set at least one of the Last-Modified
or Etag
response headers
before calling this method. Otherwise, a comparison will not be possible.
Parameters
- $request : ServerRequest
-
Request object
Return values
bool —Whether the response is 'modified' based on cache headers.
mapType()
Maps a content-type back to an alias
public
mapType(array<string|int, mixed>|string $ctype) : array<string|int, mixed>|string|null
e.g mapType('application/pdf'); // returns 'pdf'
Parameters
- $ctype : array<string|int, mixed>|string
-
Either a string content type to map, or an array of types.
Return values
array<string|int, mixed>|string|null —Aliases for the types provided.
notModified()
Sets the response as Not Modified by removing any body contents setting the status code to "304 Not Modified" and removing all conflicting headers
public
notModified() : void
Use withNotModified()
instead.
Warning This method mutates the response in-place and should be avoided.
outputCompressed()
Returns whether the resulting output will be compressed by PHP
public
outputCompressed() : bool
Return values
boolsetTypeMap()
Sets a content type definition into the map.
public
setTypeMap(string $type, array<string|int, string>|string $mimeType) : void
E.g.: setTypeMap('xhtml', ['application/xhtml+xml', 'application/xhtml'])
This is needed for RequestHandlerComponent and recognition of types.
Parameters
- $type : string
-
Content type.
- $mimeType : array<string|int, string>|string
-
Definition of the mime type.
withAddedHeader()
Return an instance with the specified header appended with the given value.
public
withAddedHeader(string $name, string|array<string|int, string> $value) : static
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.
Parameters
- $name : string
-
Case-insensitive header field name to add.
- $value : string|array<string|int, string>
-
Header value(s).
Tags
Return values
staticwithAddedLink()
Create a new response with the Link header set.
public
withAddedLink(string $url[, array<string, mixed> $options = [] ]) : static
Examples
$response = $response->withAddedLink('http://example.com?page=1', ['rel' => 'prev'])
->withAddedLink('http://example.com?page=3', ['rel' => 'next']);
Will generate:
Link: <http://example.com?page=1>; rel="prev"
Link: <http://example.com?page=3>; rel="next"
Parameters
- $url : string
-
The LinkHeader url.
- $options : array<string, mixed> = []
-
The LinkHeader params.
Tags
Return values
staticwithBody()
Return an instance with the specified message body.
public
withBody(StreamInterface $body) : static
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.
Parameters
- $body : StreamInterface
-
Body.
Tags
Return values
staticwithCache()
Create a new instance with the headers to enable client caching.
public
withCache(string|int $since[, string|int $time = '+1 day' ]) : static
Parameters
- $since : string|int
-
a valid time since the response text has not been modified
- $time : string|int = '+1 day'
-
a valid time for cache expiry
Return values
staticwithCharset()
Get a new instance with an updated charset.
public
withCharset(string $charset) : static
Parameters
- $charset : string
-
Character set string.
Return values
staticwithCookie()
Create a new response with a cookie set.
public
withCookie(CookieInterface $cookie) : static
Example
// add a cookie object
$response = $response->withCookie(new Cookie('remember_me', 1));
Parameters
- $cookie : CookieInterface
-
cookie object
Return values
staticwithCookieCollection()
Get a new instance with provided cookie collection.
public
withCookieCollection(CookieCollection $cookieCollection) : static
Parameters
- $cookieCollection : CookieCollection
-
Cookie collection to set.
Return values
staticwithDisabledCache()
Create a new instance with headers to instruct the client to not cache the response
public
withDisabledCache() : static
Return values
staticwithDownload()
Create a new instance with the Content-Disposition header set.
public
withDownload(string $filename) : static
Parameters
- $filename : string
-
The name of the file as the browser will download the response
Return values
staticwithEtag()
Create a new instance with the Etag header set.
public
withEtag(string $hash[, bool $weak = false ]) : static
Etags are a strong indicative that a response can be cached by a HTTP client. A bad way of generating Etags is creating a hash of the response output, instead generate a unique hash of the unique components that identifies a request, such as a modification time, a resource Id, and anything else you consider it that makes the response unique.
The second parameter is used to inform clients that the content has changed, but semantically it is equivalent to existing cached values. Consider a page with a hit counter, two different page views are equivalent, but they differ by a few bytes. This permits the Client to decide whether they should use the cached data.
Parameters
- $hash : string
-
The unique hash that identifies this response
- $weak : bool = false
-
Whether the response is semantically the same as other with the same hash or not. Defaults to false
Return values
staticwithExpiredCookie()
Create a new response with an expired cookie set.
public
withExpiredCookie(CookieInterface $cookie) : static
Example
// add a cookie object
$response = $response->withExpiredCookie(new Cookie('remember_me'));
Parameters
- $cookie : CookieInterface
-
cookie object
Return values
staticwithExpires()
Create a new instance with the Expires header set.
public
withExpires(DateTimeInterface|string|int|null $time) : static
Examples:
// Will Expire the response cache now
$response->withExpires('now')
// Will set the expiration in next 24 hours
$response->withExpires(new DateTime('+1 day'))
Parameters
- $time : DateTimeInterface|string|int|null
-
Valid time string or \DateTime instance.
Return values
staticwithFile()
Create a new instance that is based on a file.
public
withFile(string $path[, array<string, mixed> $options = [] ]) : static
This method will augment both the body and a number of related headers.
If $_SERVER['HTTP_RANGE']
is set, a slice of the file will be
returned instead of the entire file.
Options keys
- name: Alternate download name
- download: If
true
sets download header and forces file to be downloaded rather than displayed inline.
Parameters
- $path : string
-
Absolute path to file.
- $options : array<string, mixed> = []
-
Options See above.
Tags
Return values
staticwithHeader()
Return an instance with the provided header, replacing any existing values of any headers with the same case-insensitive name.
public
withHeader(string $name, string|array<string|int, string> $value) : static
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.
Parameters
- $name : string
-
Case-insensitive header field name.
- $value : string|array<string|int, string>
-
Header value(s).
Tags
Return values
staticwithLength()
Create a new response with the Content-Length header set.
public
withLength(string|int $bytes) : static
Parameters
- $bytes : string|int
-
Number of bytes
Return values
staticwithLocation()
Return an instance with an updated location header.
public
withLocation(string $url) : static
If the current status code is 200, it will be replaced with 302.
Parameters
- $url : string
-
The location to redirect to.
Return values
static —A new response with the Location header set.
withMaxAge()
Create an instance with Cache-Control max-age directive set.
public
withMaxAge(int $seconds) : static
The max-age is the number of seconds after which the response should no longer be considered a good candidate to be fetched from the local (client) cache.
Parameters
- $seconds : int
-
The seconds a cached response can be considered valid
Return values
staticwithModified()
Create a new instance with the Last-Modified header set.
public
withModified(DateTimeInterface|string|int $time) : static
Examples:
// Will Expire the response cache now
$response->withModified('now')
// Will set the expiration in next 24 hours
$response->withModified(new DateTime('+1 day'))
Parameters
- $time : DateTimeInterface|string|int
-
Valid time string or \DateTime instance.
Return values
staticwithMustRevalidate()
Create an instance with Cache-Control must-revalidate directive set.
public
withMustRevalidate(bool $enable) : static
Sets the Cache-Control must-revalidate directive. must-revalidate indicates that the response should not be served stale by a cache under any circumstance without first revalidating with the origin.
Parameters
- $enable : bool
-
If boolean sets or unsets the directive.
Return values
staticwithNotModified()
Create a new instance as 'not modified'
public
withNotModified() : static
This will remove any body contents set the status code to "304" and removing headers that describe a response body.
Return values
staticwithoutHeader()
Return an instance without the specified header.
public
withoutHeader(string $name) : static
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.
Parameters
- $name : string
-
Case-insensitive header field name to remove.
Return values
staticwithProtocolVersion()
Return an instance with the specified HTTP protocol version.
public
withProtocolVersion(string $version) : static
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.
Parameters
- $version : string
-
HTTP protocol version
Return values
staticwithSharable()
Create a new instace with the public/private Cache-Control directive set.
public
withSharable(bool $public[, int|null $time = null ]) : static
Parameters
- $public : bool
-
If set to true, the Cache-Control header will be set as public if set to false, the response will be set to private.
- $time : int|null = null
-
time in seconds after which the response should no longer be considered fresh.
Return values
staticwithSharedMaxAge()
Create a new instance with the Cache-Control s-maxage directive.
public
withSharedMaxAge(int $seconds) : static
The max-age is the number of seconds after which the response should no longer be considered a good candidate to be fetched from a shared cache (like in a proxy server).
Parameters
- $seconds : int
-
The number of seconds for shared max-age
Return values
staticwithStatus()
Return an instance with the specified status code and, optionally, reason phrase.
public
withStatus(int $code[, string $reasonPhrase = '' ]) : static
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.
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 status and reason phrase.
If the status code is 304 or 204, the existing Content-Type header will be cleared, as these response codes have no body.
There are external packages such as fig/http-message-util
that provide HTTP
status code constants. These can be used with any method that accepts or
returns a status code integer. However, keep in mind that these constants
might include status codes that are now allowed which will throw an
\InvalidArgumentException
.
Parameters
- $code : int
-
The 3-digit integer status code to set.
- $reasonPhrase : string = ''
-
The reason phrase to use with the provided status code; if none is provided, implementations MAY use the defaults as suggested in the HTTP specification.
Tags
Return values
staticwithStringBody()
Convenience method to set a string into the response body
public
withStringBody(string|null $string) : static
Parameters
- $string : string|null
-
The string to be sent
Return values
staticwithType()
Get an updated response with the content type set.
public
withType(string $contentType) : static
If you attempt to set the type on a 304 or 204 status code response, the content type will not take effect as these status codes do not have content-types.
Parameters
- $contentType : string
-
Either a file extension which will be mapped to a mime-type or a concrete mime-type.
Return values
staticwithVary()
Create a new instance with the Vary header set.
public
withVary(array<string|int, string>|string $cacheVariances) : static
If an array is passed values will be imploded into a comma separated string. If no parameters are passed, then an array with the current Vary header value is returned
Parameters
- $cacheVariances : array<string|int, string>|string
-
A single Vary string or an array containing the list for variances.
Return values
static_clearHeader()
Clear header
protected
_clearHeader(string $header) : void
Parameters
- $header : string
-
Header key.
Tags
_createStream()
Creates the stream object.
protected
_createStream() : void
_fileRange()
Apply a file range to a file and set the end offset.
protected
_fileRange(SplFileInfo $file, string $httpRange) : void
If an invalid range is requested a 416 Status code will be used in the response.
Parameters
- $file : SplFileInfo
-
The file to set a range on.
- $httpRange : string
-
The range to use.
_getUTCDate()
Returns a DateTime object initialized at the $time param and using UTC as timezone
protected
_getUTCDate([DateTimeInterface|string|int|null $time = null ]) : DateTimeInterface
Parameters
- $time : DateTimeInterface|string|int|null = null
-
Valid time string or \DateTimeInterface instance.
Return values
DateTimeInterface_setCacheControl()
Helper method to generate a valid Cache-Control header from the options set in other methods
protected
_setCacheControl() : void
_setContentType()
Formats the Content-Type header based on the configured contentType and charset the charset will only be set in the header if the response is of type text/*
protected
_setContentType(string $type) : void
Parameters
- $type : string
-
The type to set.
_setHeader()
Sets a header.
protected
_setHeader(string $header, string $value) : void
Parameters
- $header : string
-
Header key.
- $value : string
-
Header value.
Tags
_setStatus()
Modifier for response status
protected
_setStatus(int $code[, string $reasonPhrase = '' ]) : void
Parameters
- $code : int
-
The status code to set.
- $reasonPhrase : string = ''
-
The response reason phrase.
Tags
resolveType()
Translate and validate content-types.
protected
resolveType(string $contentType) : string
Parameters
- $contentType : string
-
The content-type or type alias.
Tags
Return values
string —The resolved content-type
validateFile()
Validate a file path is a valid response body.
protected
validateFile(string $path) : SplFileInfo
Parameters
- $path : string
-
The path to the file.
Tags
Return values
SplFileInfoassertHeader()
Ensure header name and values are valid.
private
assertHeader(string $name) : void
Parameters
- $name : string
Tags
filterHeaderValue()
private
filterHeaderValue(mixed $values) : array<int, string>
Parameters
- $values : mixed
Return values
array<int, string>getStream()
private
getStream(StreamInterface|string|resource $stream, string $modeIfNotInstance) : StreamInterface
Parameters
- $stream : StreamInterface|string|resource
- $modeIfNotInstance : string
Return values
StreamInterfacesetHeaders()
Filter a set of headers to ensure they are in the correct internal format.
private
setHeaders(array<string|int, mixed> $originalHeaders) : void
Used by message constructors to allow setting all initial headers at once.
Parameters
- $originalHeaders : array<string|int, mixed>
-
Headers to filter.
validateProtocolVersion()
Validate the HTTP protocol version
private
validateProtocolVersion(string $version) : void
Parameters
- $version : string