A class that helps wrap Request information and particulars about a single request.
Provides methods commonly used to introspect on the request headers and request body.
array
Instance cache for results of is(something) calls
(array|callable)[]
The built in detectors used with is()
can be modified with addDetector()
.
array
Array of environment data.
array
Store the additional attributes attached to the request.
string
Base URL path.
array
Array of cookie data.
array|object|null
Array of POST data. Will contain form data as well as uploaded files.
array
A list of propertes that emulated by the PSR7 attribute methods.
array
Array of parameters parsed from the URL.
string|null
The HTTP protocol version used.
array
Array of query string arguments
string|null
The request target if overridden
\Cake\Http\Session
Instance of a Session object relative to this request
\Psr\Http\Message\StreamInterface
Request body stream. Contains php://input unless input
constructor option is used.
bool
Whether or not to trust HTTP_X headers set by most load balancers.
string[]
Trusted proxies list
array
Array of Psr\Http\Message\UploadedFileInterface objects.
\Psr\Http\Message\UriInterface
Uri instance
string
webroot path segment for the request.
Get the languages accepted by the client, or check if a specific language is accepted.
Find out which content types the client accepts or check if they accept a particular type of content.
Allow only certain HTTP request methods, if the request method does not match a 405 error will be shown and the required "Allow" response header will be set.
Provides a safe accessor for request data. Allows you to use Hash::get() compatible paths.
Get all the query parameters in accordance to the PSR-7 specifications. To read specific query values use the alternative getQuery() method.
Read data from php://input
. Useful when interacting with XML or JSON request body content.
Parse the HTTP_ACCEPT header and return a sorted array with content types as the keys, and pref values as the values.
Set environment vars based on url
option to facilitate UriInterface instance generation.
Replace the cookies in the request with those contained in the provided CookieCollection.
__call(string $name, array $params)
Missing method handler, handles wrapping older style isAjax() type methods
string
$name The method called
array
$params Array of parameters for the method call
mixed
BadMethodCallException
__construct(array $config)
Create a new request object.
You can supply the data as either an array or as a string. If you use a string you can only supply the URL for the request. Using an array will let you provide the following keys:
post
POST data or non query string dataquery
Additional data from the query string.files
Uploaded files in a normalized structure, with each leaf an instance of UploadedFileInterface.cookies
Cookies for this request.environment
$_SERVER and $_ENV data.url
The URL without the base path for the request.uri
The PSR7 UriInterface object. If null, one will be created from url
or environment
.base
The base URL for the request.webroot
The webroot directory for the request.input
The data that would come from php://input this is useful for simulating requests with put, patch or delete data.session
An instance of a Session objectarray
$config optional An array of request data to create a request with.
_acceptHeaderDetector(array $detect)
Detects if a specific accept header is present.
array
$detect Detector options array.
bool
Whether or not the request is the type you are checking.
_environmentDetector(array $detect)
Detects if a specific environment variable is present.
array
$detect Detector options array.
bool
Whether or not the request is the type you are checking.
_headerDetector(array $detect)
Detects if a specific header is present.
array
$detect Detector options array.
bool
Whether or not the request is the type you are checking.
_is(string $type, array $args)
Worker for the public is() function
string
$type The type of request you want to check.
array
$args Array of custom detector arguments.
bool
Whether or not the request is the type you are checking.
_paramDetector(array $detect)
Detects if a specific request parameter is present.
array
$detect Detector options array.
bool
Whether or not the request is the type you are checking.
_parseAcceptWithQualifier(string $header)
Parse Accept* headers with qualifier options.
Only qualifiers will be extracted, any other accept extensions will be discarded as they are not frequently used.
string
$header Header to parse.
array
_setConfig(array $config)
Process the config/settings data into properties.
array
$config The config data to use.
acceptLanguage(?string $language)
Get the languages accepted by the client, or check if a specific language is accepted.
Get the list of accepted languages:
\Cake\Http\ServerRequest::acceptLanguage();
Check if a specific language is accepted:
\Cake\Http\ServerRequest::acceptLanguage('es-es');
string|null
$language optional The language to test.
array|bool
If a $language is provided, a boolean. Otherwise the array of accepted languages.
accepts(?string $type)
Find out which content types the client accepts or check if they accept a particular type of content.
$this->request->accepts();
$this->request->accepts('application/json');
This method will order the returned content types by the preference values indicated by the client.
string|null
$type optional The content type to check for. Leave null to get all types a client accepts.
array|bool
Either an array of all the types the client accepts or a boolean if they accept the provided type.
addDetector(string $name, mixed $callable)
Add a new detector to the list of detectors that a request can use.
There are several different types of detectors that can be set.
Callback detectors allow you to provide a callable to handle the check. The callback will receive the request object as its only parameter.
addDetector('custom', function ($request) { //Return a boolean });
An environment value comparison, compares a value fetched from env()
to a known value the environment value is equality checked against the provided value.
addDetector('post', ['env' => 'REQUEST_METHOD', 'value' => 'POST']);
Allows for custom detectors on the request parameters.
addDetector('admin', ['param' => 'prefix', 'value' => 'admin']);
Allows for detector to compare against Accept header value.
addDetector('csv', ['accept' => 'text/csv']);
Allows for one or more headers to be compared.
addDetector('fancy', ['header' => ['X-Fancy' => 1]);
The param
, env
and comparison types allow the following value comparison options:
Pattern value comparison allows you to compare a value fetched from env()
to a regular expression.
addDetector('iphone', ['env' => 'HTTP_USER_AGENT', 'pattern' => '/iPhone/i']);
Option based comparisons use a list of options to create a regular expression. Subsequent calls to add an already defined options detector will merge the options.
addDetector('mobile', ['env' => 'HTTP_USER_AGENT', 'options' => ['Fennec']]);
You can also make compare against multiple values using the options
key. This is useful when you want to check if a request value is in a list of options.
addDetector('extension', ['param' => '_ext', 'options' => ['pdf', 'csv']]
string
$name The name of the detector.
callable|array
$callable A callable or options array for the detector definition.
allowMethod(mixed $methods)
Allow only certain HTTP request methods, if the request method does not match a 405 error will be shown and the required "Allow" response header will be set.
Example:
$this->request->allowMethod('post'); or $this->request->allowMethod(['post', 'delete']);
If the request would be GET, response header "Allow: POST, DELETE" will be set and a 405 error will be returned.
string|array
$methods Allowed HTTP request methods.
true
Cake\Http\Exception\MethodNotAllowedException
clearDetectorCache()
Clears the instance detector cache, used by the is() function
clientIp()
Get the IP the client is using, or says they are using.
string
The client IP.
contentType()
Get the content type used in this request.
string|null
domain(int $tldLength)
Get the domain name and include $tldLength segments of the tld.
int
$tldLength optional Number of segments your tld contains. For example: example.com
contains 1 tld. While example.co.uk
contains 2.
string
Domain name without subdomains.
getAttribute(mixed $name, mixed $default)
Read an attribute from the request, or get the default
string
$name The attribute name.
mixed|null
$default optional The default value if the attribute has not been set.
mixed
getAttributes()
Get all the attributes in the request.
This will include the params, webroot, base, and here attributes that CakePHP provides.
array
getBody()
Gets the body of the message.
\Psr\Http\Message\StreamInterface
Returns the body as a stream.
getCookie(string $key, mixed $default)
Read cookie data from the request's cookie data.
string
$key The key or dotted path you want to read.
string|array|null
$default optional The default value if the cookie is not set.
string|array|null
Either the cookie value, or null if the value doesn't exist.
getCookieCollection()
Get a cookie collection based on the request's cookies
The CookieCollection lets you interact with request cookies using \Cake\Http\Cookie\Cookie
objects and can make converting request cookies into response cookies easier.
This method will create a new cookie collection each time it is called. This is an optimization that allows fewer objects to be allocated until the more complex CookieCollection is needed. In general you should prefer getCookie()
and getCookieParams()
over this method. Using a CookieCollection is ideal if your cookies contain complex JSON encoded data.
\Cake\Http\Cookie\CookieCollection
getCookieParams()
Get all the cookie data from the request.
array
An array of cookie data.
getData(?string $name, mixed $default)
Provides a safe accessor for request data. Allows you to use Hash::get() compatible paths.
// get all data $request->getData(); // Read a specific field. $request->getData('Post.title'); // With a default value. $request->getData('Post.not there', 'default value');
When reading values you will get null
for keys/values that do not exist.
Developers are encouraged to use getParsedBody() if they need the whole data array, as it is PSR-7 compliant, and this method is not. Using Hash::get() you can also get single params.
$value = Hash::get($request->getParsedBody(), 'Post.id');
string|null
$name optional Dot separated name of the value to read. Or null to read all data.
mixed
$default optional The default data.
mixed
The value being read.
getEnv(string $key, ?string $default)
Get a value from the request's environment data.
Fallback to using env() if the key is not set in the $environment property.
string
$key The key you want to read from.
string|null
$default optional Default value when trying to retrieve an environment variable's value that does not exist.
string|null
Either the environment value, or null if the value doesn't exist.
getHeader(mixed $name)
Get a single header from the request.
Return the header value as an array. If the header is not present an empty array will be returned.
string
$name The header you want to get (case-insensitive)
string[]
An associative array of headers and their values. If the header doesn't exist, an empty array will be returned.
getHeaderLine(mixed $name)
Get a single header as a string from the request.
string
$name The header you want to get (case-insensitive)
string
Header values collapsed into a comma separated string.
getHeaders()
Get all headers in the request.
Returns an associative array where the header names are the keys and the values are a list of header values.
While header names are not case-sensitive, getHeaders() will normalize the headers.
string[][]
An associative array of headers and their values.
getMethod()
Get the HTTP method used for this request.
There are a few ways to specify a method.
_method
Any of these 3 approaches can be used to set the HTTP method used by CakePHP internally, and will effect the result of this method.
string
The name of the HTTP method used.
getParam(string $name, mixed $default)
Safely access the values in $this->params.
string
$name The name or dotted path to parameter.
mixed
$default optional The default value if $name
is not set. Default null
.
mixed
getParsedBody()
Get the parsed request body data.
If the request Content-Type is either application/x-www-form-urlencoded or multipart/form-data, and the request method is POST, this will be the post data. For other content types, it may be the deserialized request body.
array|object|null
The deserialized body parameters, if any. These will typically be an array.
getPath()
Get the path of current request.
string
getProtocolVersion()
Retrieves the HTTP protocol version as a string.
string
HTTP protocol version.
getQuery(?string $name, mixed $default)
Read a specific query value or dotted path.
Developers are encouraged to use getQueryParams() if they need the whole query array, as it is PSR-7 compliant, and this method is not. Using Hash::get() you can also get single params.
$value = Hash::get($request->getQueryParams(), 'Post.id');
string|null
$name optional The name or dotted path to the query param or null to read all.
mixed
$default optional The default value if the named parameter is not set, and $name is not null.
array|string|null
Query data.
getQueryParams()
Get all the query parameters in accordance to the PSR-7 specifications. To read specific query values use the alternative getQuery() method.
array
getRequestTarget()
Retrieves the request's target.
Retrieves the message's request-target either as it was requested, or as set with withRequestTarget()
. By default this will return the application relative path without base directory, and the query string defined in the SERVER environment.
string
getServerParams()
Get all the server environment parameters.
Read all of the 'environment' or 'server' data that was used to create this request.
array
getSession()
Returns the instance of the Session object for this request
\Cake\Http\Session
getTrustedProxies()
Get trusted proxies
string[]
getUploadedFile(string $path)
Get the uploaded file from a dotted path.
string
$path The dot separated path to the file you want.
\Psr\Http\Message\UploadedFileInterface|null
getUploadedFiles()
Get the array of uploaded files from the request.
array
getUri()
Retrieves the URI instance.
\Psr\Http\Message\UriInterface
Returns a UriInterface instance representing the URI of the request.
hasHeader(mixed $name)
Check if a header is set in the request.
string
$name The header you want to get (case-insensitive)
bool
Whether or not the header is defined.
host()
Get the host that the request was handled on.
string|null
input(?callable $callback, mixed ...$args)
Read data from php://input
. Useful when interacting with XML or JSON request body content.
Getting input with a decoding function:
$this->request->input('json_decode');
Getting input using a decoding function, and additional params:
$this->request->input('Xml::build', ['return' => 'DOMDocument']);
Any additional parameters are applied to the callback in the order they are given.
callable|null
$callback optional A decoding callback that will convert the string data to another representation. Leave empty to access the raw input data. You can also supply additional parameters for the decoding callback using var args, see above.
mixed
...$args The additional arguments
mixed
The decoded/processed request data.
is(mixed $type, mixed ...$args)
Check whether or not a Request is a certain type.
Uses the built in detection rules as well as additional rules defined with Cake\Http\ServerRequest::addDetector(). Any detector can be called as is($type)
or is$Type()
.
string|string[]
$type The type of request you want to check. If an array this method will return true if the request matches any type.
string
...$args List of arguments
bool
Whether or not the request is the type you are checking.
isAll(array $types)
Check that a request matches all the given types.
Allows you to test multiple types and union the results. See Request::is() for how to add additional types and the built-in types.
string[]
$types The types to check.
bool
Success.
normalizeHeaderName(string $name)
Normalize a header name into the SERVER version.
string
$name The header name.
string
The normalized header name.
parseAccept()
Parse the HTTP_ACCEPT header and return a sorted array with content types as the keys, and pref values as the values.
Generally you want to use Cake\Http\ServerRequest::accept() to get a simple list of the accepted content types.
array
An array of prefValue => [content/types]
port()
Get the port the request was handled on.
string|null
processUrlOption(array $config)
Set environment vars based on url
option to facilitate UriInterface instance generation.
query
option is also updated based on URL's querystring.
array
$config Config array.
array
Update config.
referer(bool $local)
Returns the referer that referred this request.
bool
$local optional Attempt to return a local address. Local addresses do not contain hostnames.
string|null
The referring address for this request or null.
scheme()
Get the current url scheme used for the request.
e.g. 'http', or 'https'
string|null
The scheme used for the request.
setTrustedProxies(array $proxies)
register trusted proxies
string[]
$proxies ips list of trusted proxies
subdomains(int $tldLength)
Get the subdomains for a host.
int
$tldLength optional Number of segments your tld contains. For example: example.com
contains 1 tld. While example.co.uk
contains 2.
string[]
An array of subdomains.
validateUploadedFiles(array $uploadedFiles, string $path)
Recursively validate uploaded file data.
array
$uploadedFiles The new files array to validate.
string
$path The path thus far.
InvalidArgumentException
withAddedHeader(mixed $name, mixed $value)
Get a modified request with the provided header.
Existing header values will be retained. The provided value will be appended into the existing values.
string
$name The header name.
string|array
$value The header value
static
withAttribute(mixed $name, mixed $value)
Return an instance with the specified request attribute.
string
$name The attribute name.
mixed
$value The value of the attribute.
static
withBody(\Psr\Http\Message\StreamInterface $body)
Return an instance with the specified message body.
\Psr\Http\Message\StreamInterface
$body The new request body
static
withCookieCollection(\Cake\Http\Cookie\CookieCollection $cookies)
Replace the cookies in the request with those contained in the provided CookieCollection.
\Cake\Http\Cookie\CookieCollection
$cookies The cookie collection
static
withCookieParams(array $cookies)
Replace the cookies and get a new request instance.
array
$cookies The new cookie data to use.
static
withData(string $name, mixed $value)
Update the request with a new request data element.
Returns an updated request object. This method returns a new request object and does not mutate the request in-place.
Use withParsedBody()
if you need to replace the all request data.
string
$name The dot separated path to insert $value at.
mixed
$value The value to insert into the request data.
static
withEnv(string $key, string $value)
Update the request with a new environment data element.
Returns an updated request object. This method returns a new request object and does not mutate the request in-place.
string
$key The key you want to write to.
string
$value Value to set
static
withHeader(mixed $name, mixed $value)
Get a modified request with the provided header.
string
$name The header name.
string|array
$value The header value
static
withMethod(mixed $method)
Update the request method and get a new instance.
string
$method The HTTP method to use.
static
A new instance with the updated method.
withParam(string $name, mixed $value)
Update the request with a new routing parameter
Returns an updated request object. This method returns a new request object and does not mutate the request in-place.
string
$name The dot separated path to insert $value at.
mixed
$value The value to insert into the the request parameters.
static
withParsedBody(mixed $data)
Update the parsed body and get a new instance.
array|object|null
$data The deserialized body data. This will typically be in an array or object.
static
withProtocolVersion(mixed $version)
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").
string
$version HTTP protocol version
static
withQueryParams(array $query)
Update the query string data and get a new instance.
array
$query The query string data to use
static
A new instance with the updated query string data.
withRequestTarget(mixed $target)
Create a new instance with a specific request-target.
You can use this method to overwrite the request target that is inferred from the request's Uri. This also lets you change the request target's form to an absolute-form, authority-form or asterisk-form
string
$target The request target.
static
withUploadedFiles(array $files)
Update the request replacing the files, and creating a new instance.
array
$files An array of uploaded file objects.
static
InvalidArgumentException
withUri(\Psr\Http\Message\UriInterface $uri, mixed $preserveHost)
Return an instance with the specified uri
Warning Replacing the Uri will not update the base
, webroot
, and url
attributes.
\Psr\Http\Message\UriInterface
$uri The new request uri
bool
$preserveHost optional Whether or not the host should be retained.
static
withoutAttribute(mixed $name)
Return an instance without the specified request attribute.
string
$name The attribute name.
static
InvalidArgumentException
withoutData(string $name)
Update the request removing a data element.
Returns an updated request object. This method returns a new request object and does not mutate the request in-place.
string
$name The dot separated path to remove.
static
withoutHeader(mixed $name)
Get a modified request without a provided header.
string
$name The header name to remove.
static
Instance cache for results of is(something) calls
array
The built in detectors used with is()
can be modified with addDetector()
.
There are several ways to specify a detector, see \Cake\Http\ServerRequest::addDetector() for the various formats and ways to define detectors.
(array|callable)[]
Array of environment data.
array
Store the additional attributes attached to the request.
array
Base URL path.
string
Array of cookie data.
array
Array of POST data. Will contain form data as well as uploaded files.
In PUT/PATCH/DELETE requests this property will contain the form-urlencoded data.
array|object|null
A list of propertes that emulated by the PSR7 attribute methods.
array
Array of parameters parsed from the URL.
array
The HTTP protocol version used.
string|null
Array of query string arguments
array
The request target if overridden
string|null
Instance of a Session object relative to this request
\Cake\Http\Session
Request body stream. Contains php://input unless input
constructor option is used.
\Psr\Http\Message\StreamInterface
Whether or not to trust HTTP_X headers set by most load balancers.
Only set to true if your application runs behind load balancers/proxies that you control.
bool
Trusted proxies list
string[]
Array of Psr\Http\Message\UploadedFileInterface objects.
array
Uri instance
\Psr\Http\Message\UriInterface
webroot path segment for the request.
string
© 2005–present The Cake Software Foundation, Inc.
Licensed under the MIT License.
CakePHP is a registered trademark of Cake Software Foundation, Inc.
We are not endorsed by or affiliated with CakePHP.
https://api.cakephp.org/4.1/class-Cake.Http.ServerRequest.html