Class ServerRequest
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.
Property Summary
- 
        $_detectorCache protectedarrayInstance cache for results of is(something) calls 
- 
        $_detectors protected staticarrayThe built in detectors used with is()can be modified withaddDetector().
- 
        $_environment protectedarrayArray of environment data. 
- 
        $_input protectedstringContents of php://input 
- 
        $attributes protectedarrayStore the additional attributes attached to the request. 
- 
        $base protected deprecatedstringBase URL path. 
- 
        $cookies protected deprecatedarrayArray of cookie data. 
- 
        $data protected deprecatednull|array|objectArray 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. 
- 
        $emulatedAttributes protectedarrayA list of propertes that emulated by the PSR7 attribute methods. 
- 
        $here protected deprecatedstringThe full address to the current request 
- 
        $params protected deprecatedarrayArray of parameters parsed from the URL. 
- 
        $protocol protectedstring|nullThe HTTP protocol version used. 
- 
        $query protected deprecatedarrayArray of query string arguments 
- 
        $requestTarget protectedstring|nullThe request target if overridden 
- 
        $session protectedCake\Http\SessionInstance of a Session object relative to this request 
- 
        $stream protectedPsr\Http\Message\StreamInterfaceRequest body stream. Contains php://input unless inputconstructor option is used.
- 
        $trustProxy publicboolWhether 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. 
- 
        $trustedProxies protectedarraytrusted proxies list 
- 
        $uploadedFiles protectedarrayArray of Psr\Http\Message\UploadedFileInterface objects. 
- 
        $uri protectedPsr\Http\Message\UriInterfaceUri instance 
- 
        $url protected deprecatedstringThe URL string used for the request. 
- 
        $webroot protected deprecatedstringwebroot path segment for the request. 
Method Summary
- 
          __call() publicMissing method handler, handles wrapping older style isAjax() type methods 
- 
          __construct() publicCreate a new request object. 
- 
          __get() public deprecatedMagic get method allows access to parsed routing parameters directly on the object. 
- 
          __isset() public deprecatedMagic isset method allows isset/empty checks on routing parameters. 
- 
          __set() public deprecatedMagic set method allows backward compatibility for former public properties 
- 
          _acceptHeaderDetector() protectedDetects if a specific accept header is present. 
- 
          _createUploadedFile() protectedCreate an UploadedFile instance from a $_FILES array. 
- 
          _environmentDetector() protectedDetects if a specific environment variable is present. 
- 
          _headerDetector() protectedDetects if a specific header is present. 
- 
          _is() protectedWorker for the public is() function 
- 
          _normalizeNestedFiles() protectedNormalize an array of file specifications. 
- 
          _paramDetector() protectedDetects if a specific request parameter is present. 
- 
          _parseAcceptWithQualifier() protectedParse Accept* headers with qualifier options. 
- 
          _processFiles() protectedProcess uploaded files and move things onto the post data. 
- 
          _processGet() protectedProcess the GET parameters and move things into the object. 
- 
          _processPost() protectedSets the REQUEST_METHOD environment variable based on the simulated _method HTTP override value. The 'ORIGINAL_REQUEST_METHOD' is also preserved, if you want the read the non-simulated HTTP method the client used. 
- 
          _readInput() protectedRead data from php://input, mocked in tests. 
- 
          _setConfig() protectedProcess the config/settings data into properties. 
- 
          acceptLanguage() publicGet the languages accepted by the client, or check if a specific language is accepted. 
- 
          accepts() publicFind out which content types the client accepts or check if they accept a particular type of content. 
- 
          addDetector() public staticAdd a new detector to the list of detectors that a request can use. There are several different formats and types of detectors that can be set. 
- 
          addParams() public deprecatedAdd parameters to the request's parsed parameter set. This will overwrite any existing parameters. This modifies the parameters available through $request->getParam().
- 
          addPaths() public deprecatedAdd paths to the requests' paths vars. This will overwrite any existing paths. Provides an easy way to modify, here, webroot and base. 
- 
          allowMethod() publicAllow 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. 
- 
          clearDetectorCache() publicClears the instance detector cache, used by the is() function 
- 
          clientIp() publicGet the IP the client is using, or says they are using. 
- 
          contentType() publicGet the content type used in this request. 
- 
          cookie() public deprecatedRead cookie data from the request's cookie data. 
- 
          createFromGlobals() public static deprecatedWrapper method to create a new request from PHP superglobals. 
- 
          data() public deprecatedProvides a read/write accessor for $this->data. Allows you to use aHash::get()compatible syntax for reading post data.
- 
          domain() publicGet the domain name and include $tldLength segments of the tld. 
- 
          env() public deprecatedGet/Set value from the request's environment data. Fallback to using env() if key not set in $environment property. 
- 
          getAttribute() publicRead an attribute from the request, or get the default 
- 
          getAttributes() publicGet all the attributes in the request. 
- 
          getBody() publicGets the body of the message. 
- 
          getCookie() publicRead cookie data from the request's cookie data. 
- 
          getCookieCollection() publicGet a cookie collection based on the request's cookies 
- 
          getCookieParams() publicGet all the cookie data from the request. 
- 
          getData() publicProvides a safe accessor for request data. Allows you to use Hash::get() compatible paths. 
- 
          getEnv() publicGet a value from the request's environment data. Fallback to using env() if the key is not set in the $environment property. 
- 
          getHeader() publicGet a single header from the request. 
- 
          getHeaderLine() publicGet a single header as a string from the request. 
- 
          getHeaders() publicGet all headers in the request. 
- 
          getMethod() publicGet the HTTP method used for this request. There are a few ways to specify a method. 
- 
          getParam() publicSafely access the values in $this->params. 
- 
          getParsedBody() publicGet the parsed request body data. 
- 
          getPath() publicGet the path of current request. 
- 
          getProtocolVersion() publicRetrieves the HTTP protocol version as a string. 
- 
          getQuery() publicRead a specific query value or dotted path. 
- 
          getQueryParams() publicGet all the query parameters in accordance to the PSR-7 specifications. To read specific query values use the alternative getQuery() method. 
- 
          getRequestTarget() publicRetrieves the request's target. 
- 
          getServerParams() publicGet all the server environment parameters. 
- 
          getSession() publicReturns the instance of the Session object for this request 
- 
          getTrustedProxies() publicGet trusted proxies 
- 
          getUploadedFile() publicGet the uploaded file from a dotted path. 
- 
          getUploadedFiles() publicGet the array of uploaded files from the request. 
- 
          getUri() publicRetrieves the URI instance. 
- 
          hasHeader() publicCheck if a header is set in the request. 
- 
          header() public deprecatedRead an HTTP header from the Request information. 
- 
          here() public deprecatedGet the value of the current requests URL. Will include the query string arguments. 
- 
          host() publicGet the host that the request was handled on. 
- 
          input() publicRead data from php://input. Useful when interacting with XML or JSON request body content.
- 
          is() publicCheck whether or not a Request is a certain type. 
- 
          isAll() publicCheck that a request matches all the given types. 
- 
          method() public deprecatedGet the HTTP method used for this request. 
- 
          normalizeHeaderName() protectedNormalize a header name into the SERVER version. 
- 
          offsetExists() public deprecatedArray access isset() implementation 
- 
          offsetGet() public deprecatedArray access read implementation 
- 
          offsetSet() public deprecatedArray access write implementation 
- 
          offsetUnset() public deprecatedArray access unset() implementation 
- 
          param() public deprecatedSafely access the values in $this->params. 
- 
          parseAccept() publicParse the HTTP_ACCEPT header and return a sorted array with content types as the keys, and pref values as the values. 
- 
          port() publicGet the port the request was handled on. 
- 
          query() public deprecatedProvides a read accessor for $this->query. Allows you to use aHash::get()compatible syntax for reading post data.
- 
          referer() publicReturns the referer that referred this request. 
- 
          scheme() publicGet the current url scheme used for the request. 
- 
          session() public deprecatedReturns the instance of the Session object for this request 
- 
          setInput() public deprecatedModify data originally from php://input. Useful for altering json/xml data in middleware or DispatcherFilters before it gets to RequestHandlerComponent
- 
          setTrustedProxies() publicregister trusted proxies 
- 
          subdomains() publicGet the subdomains for a host. 
- 
          validateUploadedFiles() protectedRecursively validate uploaded file data. 
- 
          withAddedHeader() publicGet a modified request with the provided header. 
- 
          withAttribute() publicReturn an instance with the specified request attribute. 
- 
          withBody() publicReturn an instance with the specified message body. 
- 
          withCookieCollection() publicReplace the cookies in the request with those contained in the provided CookieCollection. 
- 
          withCookieParams() publicReplace the cookies and get a new request instance. 
- 
          withData() publicUpdate the request with a new request data element. 
- 
          withEnv() publicUpdate the request with a new environment data element. 
- 
          withHeader() publicGet a modified request with the provided header. 
- 
          withMethod() publicUpdate the request method and get a new instance. 
- 
          withParam() publicUpdate the request with a new routing parameter 
- 
          withParsedBody() publicUpdate the parsed body and get a new instance. 
- 
          withProtocolVersion() publicReturn an instance with the specified HTTP protocol version. 
- 
          withQueryParams() publicUpdate the query string data and get a new instance. 
- 
          withRequestTarget() publicCreate a new instance with a specific request-target. 
- 
          withUploadedFiles() publicUpdate the request replacing the files, and creating a new instance. 
- 
          withUri() publicReturn an instance with the specified uri 
- 
          withoutAttribute() publicReturn an instance without the specified request attribute. 
- 
          withoutData() publicUpdate the request removing a data element. 
- 
          withoutHeader() publicGet a modified request without a provided header. 
Method Detail
__call() ¶ public
__call(string $name, array $params): mixedMissing method handler, handles wrapping older style isAjax() type methods
Parameters
- 
                string$name
- The method called 
- 
                array$params
- Array of parameters for the method call 
Returns
mixedThrows
BadMethodCallExceptionwhen an invalid method is called.
__construct() ¶ public
__construct(string|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:
- postPOST data or non query string data
- queryAdditional data from the query string.
- filesUploaded file data formatted like $_FILES.
- cookiesCookies for this request.
- environment$_SERVER and $_ENV data.
- urlThe URL without the base path for the request.
- uriThe PSR7 UriInterface object. If null, one will be created.
- baseThe base URL for the request.
- webrootThe webroot directory for the request.
- inputThe data that would come from php://input this is useful for simulating requests with put, patch or delete data.
- sessionAn instance of a Session object
Parameters
- 
                string|array$config optional
- An array of request data to create a request with. The string version of this argument is deprecated and will be removed in 4.0.0 
__get() ¶ public
__get(string $name): mixedMagic get method allows access to parsed routing parameters directly on the object.
Allows access to $this->params['controller'] via $this->controller
Parameters
- 
                string$name
- The property being accessed. 
Returns
mixedEither the value of the parameter or null.
__isset() ¶ public
__isset(string $name): boolMagic isset method allows isset/empty checks on routing parameters.
Parameters
- 
                string$name
- The property being accessed. 
Returns
boolExistence
__set() ¶ public
__set(string $name, mixed $value): mixedMagic set method allows backward compatibility for former public properties
Parameters
- 
                string$name
- The property being accessed. 
- 
                mixed$value
- The property value. 
Returns
mixedEither the value of the parameter or null.
_acceptHeaderDetector() ¶ protected
_acceptHeaderDetector(array $detect): boolDetects if a specific accept header is present.
Parameters
- 
                array$detect
- Detector options array. 
Returns
boolWhether or not the request is the type you are checking.
_createUploadedFile() ¶ protected
_createUploadedFile(array $value): array|UploadedFileInterfaceCreate an UploadedFile instance from a $_FILES array.
If the value represents an array of values, this method will recursively process the data.
Parameters
- 
                array$value
- $_FILES struct 
Returns
array|UploadedFileInterface_environmentDetector() ¶ protected
_environmentDetector(array $detect): boolDetects if a specific environment variable is present.
Parameters
- 
                array$detect
- Detector options array. 
Returns
boolWhether or not the request is the type you are checking.
_headerDetector() ¶ protected
_headerDetector(array $detect): boolDetects if a specific header is present.
Parameters
- 
                array$detect
- Detector options array. 
Returns
boolWhether or not the request is the type you are checking.
_is() ¶ protected
_is(string $type, array $args): boolWorker for the public is() function
Parameters
- 
                string$type
- The type of request you want to check. 
- 
                array$args
- Array of custom detector arguments. 
Returns
boolWhether or not the request is the type you are checking.
_normalizeNestedFiles() ¶ protected
_normalizeNestedFiles(array $files = []): arrayNormalize an array of file specifications.
Loops through all nested files and returns a normalized array of UploadedFileInterface instances.
Parameters
- 
                array$files optional
- The file data to normalize & convert. 
Returns
arrayAn array of UploadedFileInterface objects.
_paramDetector() ¶ protected
_paramDetector(array $detect): boolDetects if a specific request parameter is present.
Parameters
- 
                array$detect
- Detector options array. 
Returns
boolWhether or not the request is the type you are checking.
_parseAcceptWithQualifier() ¶ protected
_parseAcceptWithQualifier(string $header): arrayParse Accept* headers with qualifier options.
Only qualifiers will be extracted, any other accept extensions will be discarded as they are not frequently used.
Parameters
- 
                string$header
- Header to parse. 
Returns
array_processFiles() ¶ protected
_processFiles(array $post, array $files): arrayProcess uploaded files and move things onto the post data.
Parameters
- 
                array$post
- Post data to merge files onto. 
- 
                array$files
- Uploaded files to merge in. 
Returns
arraymerged post + file data.
_processGet() ¶ protected
_processGet(array $query, string $queryString = ''): arrayProcess the GET parameters and move things into the object.
Parameters
- 
                array$query
- The array to which the parsed keys/values are being added. 
- 
                string$queryString optional
- A query string from the URL if provided 
Returns
arrayAn array containing the parsed query string as keys/values.
_processPost() ¶ protected
_processPost(array $data): arraySets the REQUEST_METHOD environment variable based on the simulated _method HTTP override value. The 'ORIGINAL_REQUEST_METHOD' is also preserved, if you want the read the non-simulated HTTP method the client used.
Parameters
- 
                array$data
- Array of post data. 
Returns
array_readInput() ¶ protected
_readInput(): stringRead data from php://input, mocked in tests.
Returns
stringcontents of php://input
_setConfig() ¶ protected
_setConfig(array $config): voidProcess the config/settings data into properties.
Parameters
- 
                array$config
- The config data to use. 
Returns
voidacceptLanguage() ¶ public
acceptLanguage(string|null $language = null): array|boolGet 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');
Parameters
- 
                string|null$language optional
- The language to test. 
Returns
array|boolIf a $language is provided, a boolean. Otherwise the array of accepted languages.
accepts() ¶ public
accepts(string|null $type = null): array|boolFind out which content types the client accepts or check if they accept a particular type of content.
Get all types:
$this->request->accepts();Check for a single type:
$this->request->accepts('application/json');This method will order the returned content types by the preference values indicated by the client.
Parameters
- 
                string|null$type optional
- The content type to check for. Leave null to get all types a client accepts. 
Returns
array|boolEither an array of all the types the client accepts or a boolean if they accept the provided type.
addDetector() ¶ public static
addDetector(string $name, callable|array $callable): voidAdd a new detector to the list of detectors that a request can use. There are several different formats and types of detectors that can be set.
Callback detectors
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 });
addDetector('custom', ['SomeClass', 'somemethod']);Environment value comparison
An environment value comparison, compares a value fetched from env() to a known value
the environment value is equality checked against the provided value.
e.g addDetector('post', ['env' => 'REQUEST_METHOD', 'value' => 'POST'])
Pattern value comparison
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 comparison
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']]);Request parameter detectors
Allows for custom detectors on the request parameters.
e.g addDetector('requested', ['param' => 'requested', 'value' => 1]
You can also make parameter detectors that accept multiple values
using the options key. This is useful when you want to check
if a request parameter is in a list of options.
addDetector('extension', ['param' => 'ext', 'options' => ['pdf', 'csv']]
Parameters
- 
                string$name
- The name of the detector. 
- 
                callable|array$callable
- A callable or options array for the detector definition. 
Returns
voidaddParams() ¶ public
addParams(array $params): $thisAdd parameters to the request's parsed parameter set. This will overwrite any existing parameters.
This modifies the parameters available through $request->getParam().
Parameters
- 
                array$params
- Array of parameters to merge in 
Returns
$thisThe current object, you can chain this method.
addPaths() ¶ public
addPaths(array $paths): $thisAdd paths to the requests' paths vars. This will overwrite any existing paths. Provides an easy way to modify, here, webroot and base.
Parameters
- 
                array$paths
- Array of paths to merge in 
Returns
$thisThe current object, you can chain this method.
allowMethod() ¶ public
allowMethod(string|array $methods): boolAllow 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.
Parameters
- 
                string|array$methods
- Allowed HTTP request methods. 
Returns
booltrue
Throws
Cake\Http\Exception\MethodNotAllowedExceptionclearDetectorCache() ¶ public
clearDetectorCache(): voidClears the instance detector cache, used by the is() function
Returns
voidclientIp() ¶ public
clientIp(): stringGet the IP the client is using, or says they are using.
Returns
stringThe client IP.
contentType() ¶ public
contentType(): stringGet the content type used in this request.
Returns
stringcookie() ¶ public
cookie(string $key): null|stringRead cookie data from the request's cookie data.
Parameters
- 
                string$key
- The key you want to read. 
Returns
null|stringEither the cookie value, or null if the value doesn't exist.
createFromGlobals() ¶ public static
createFromGlobals(): selfWrapper method to create a new request from PHP superglobals.
Uses the $_GET, $_POST, $_FILES, $_COOKIE, $_SERVER, $_ENV and php://input data to construct the request.
Returns
selfdata() ¶ public
data(string|null $name = null, mixed ...$args): mixed|$thisProvides a read/write accessor for $this->data.
Allows you to use a Hash::get() compatible syntax for reading post data.
Reading values.
$request->data('Post.title');When reading values you will get null for keys/values that do not exist.
Writing values
$request->data('Post.title', 'New post!');You can write to any value, even paths/keys that do not exist, and the arrays will be created for you.
Parameters
- 
                string|null$name optional
- Dot separated name of the value to read/write 
- 
                mixed...$args
- The data to set (deprecated) 
Returns
mixed|$thisEither the value being read, or this so you can chain consecutive writes.
domain() ¶ public
domain(int $tldLength = 1): stringGet the domain name and include $tldLength segments of the tld.
Parameters
- 
                int$tldLength optional
- Number of segments your tld contains. For example: - example.comcontains 1 tld. While- example.co.ukcontains 2.
Returns
stringDomain name without subdomains.
env() ¶ public
env(string $key, string|null $value = null, string|null $default = null): $this|string|nullGet/Set value from the request's environment data. Fallback to using env() if key not set in $environment property.
Parameters
- 
                string$key
- The key you want to read/write from/to. 
- 
                string|null$value optional
- Value to set. Default null. 
- 
                string|null$default optional
- Default value when trying to retrieve an environment variable's value that does not exist. The value parameter must be null. 
Returns
$this|string|nullThis instance if used as setter, if used as getter either the environment value, or null if the value doesn't exist.
getAttribute() ¶ public
getAttribute(string $name, mixed $default = null): mixedRead an attribute from the request, or get the default
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.
Parameters
- 
                string$name
- The attribute name. 
- 
                mixed$default optional
- The default value if the attribute has not been set. 
Returns
mixedgetAttributes() ¶ public
getAttributes(): arrayGet all the attributes in the request.
This will include the params, webroot, base, and here attributes that CakePHP provides.
Returns
arraygetBody() ¶ public
getBody(): Psr\Http\Message\StreamInterfaceGets the body of the message.
Returns
Psr\Http\Message\StreamInterfaceReturns the body as a stream.
getCookie() ¶ public
getCookie(string $key, string $default = null): null|array|stringRead cookie data from the request's cookie data.
Parameters
- 
                string$key
- The key or dotted path you want to read. 
- 
                string$default optional
- The default value if the cookie is not set. 
Returns
null|array|stringEither the cookie value, or null if the value doesn't exist.
getCookieCollection() ¶ public
getCookieCollection(): Cake\Http\Cookie\CookieCollectionGet 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.
Returns
Cake\Http\Cookie\CookieCollectiongetCookieParams() ¶ public
getCookieParams(): arrayGet all the cookie data from the request.
Retrieves cookies sent by the client to the server.
The data MUST be compatible with the structure of the $_COOKIE superglobal.
Returns
arrayAn array of cookie data.
getData() ¶ public
getData(string|null $name = null, mixed $default = null): null|string|arrayProvides a safe accessor for request data. Allows you to use Hash::get() compatible paths.
Reading values.
// 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.
Parameters
- 
                string|null$name optional
- Dot separated name of the value to read. Or null to read all data. 
- 
                mixed$default optional
- The default data. 
Returns
null|string|arrayThe value being read.
getEnv() ¶ public
getEnv(string $key, string|null $default = null): string|nullGet a value from the request's environment data. Fallback to using env() if the key is not set in the $environment property.
Parameters
- 
                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. 
Returns
string|nullEither the environment value, or null if the value doesn't exist.
getHeader() ¶ public
getHeader(string $name): arrayGet 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.
Parameters
- 
                string$name
- The header you want to get (case-insensitive) 
Returns
arrayAn associative array of headers and their values. If the header doesn't exist, an empty array will be returned.
Links
getHeaderLine() ¶ public
getHeaderLine(string $name): stringGet a single header as a string from the request.
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
- 
                string$name
- The header you want to get (case-insensitive) 
Returns
stringHeader values collapsed into a comma separated string.
Links
getHeaders() ¶ public
getHeaders(): arrayGet 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.
Returns
arrayAn associative array of headers and their values.
Links
getMethod() ¶ public
getMethod(): stringGet the HTTP method used for this request. There are a few ways to specify a method.
- If your client supports it you can use native HTTP methods.
- You can set the HTTP-X-Method-Override header.
- You can submit an input with the name _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.
Returns
stringThe name of the HTTP method used.
Links
getParam() ¶ public
getParam(string $name, mixed $default = false): mixedSafely access the values in $this->params.
Parameters
- 
                string$name
- The name or dotted path to parameter. 
- 
                mixed$default optional
- The default value if - $nameis not set. Default- false.
Returns
mixedgetParsedBody() ¶ public
getParsedBody(): null|array|objectGet 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.
Returns
null|array|objectThe deserialized body parameters, if any. These will typically be an array or object.
getProtocolVersion() ¶ public
getProtocolVersion(): stringRetrieves the HTTP protocol version as a string.
The string MUST contain only the HTTP version number (e.g., "1.1", "1.0").
Returns
stringHTTP protocol version.
getQuery() ¶ public
getQuery(string|null $name = null, mixed $default = null): null|string|arrayRead a specific query value or dotted path.
Developers are encouraged to use getQueryParams() when possible as it is PSR-7 compliant, and this method is not.
PSR-7 Alternative
$value = Hash::get($request->getQueryParams(), 'Post.id', null);Parameters
- 
                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. 
Returns
null|string|arrayQuery data.
See Also
getQueryParams() ¶ public
getQueryParams(): arrayGet all the query parameters in accordance to the PSR-7 specifications. To read specific query values use the alternative getQuery() method.
Retrieves the deserialized query string arguments, if any.
Note: the query params might not be in sync with the URI or server
params. If you need to ensure you are only getting the original
values, you may need to parse the query string from getUri()->getQuery()
or from the QUERY_STRING server param.
Returns
arrayLinks
getRequestTarget() ¶ public
getRequestTarget(): stringRetrieves 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.
Returns
stringgetServerParams() ¶ public
getServerParams(): arrayGet all the server environment parameters.
Read all of the 'environment' or 'server' data that was used to create this request.
Returns
arrayLinks
getSession() ¶ public
getSession(): Cake\Http\SessionReturns the instance of the Session object for this request
Returns
Cake\Http\SessiongetUploadedFile() ¶ public
getUploadedFile(string $path): null|Psr\Http\Message\UploadedFileInterfaceGet the uploaded file from a dotted path.
Parameters
- 
                string$path
- The dot separated path to the file you want. 
Returns
null|Psr\Http\Message\UploadedFileInterfacegetUploadedFiles() ¶ public
getUploadedFiles(): arrayGet the array of uploaded files from the request.
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().
Returns
arraygetUri() ¶ public
getUri(): Psr\Http\Message\UriInterfaceRetrieves the URI instance.
This method MUST return a UriInterface instance.
Returns
Psr\Http\Message\UriInterfaceReturns a UriInterface instance representing the URI of the request.
hasHeader() ¶ public
hasHeader(string $name): boolCheck if a header is set in the request.
Parameters
- 
                string$name
- The header you want to get (case-insensitive) 
Returns
boolWhether or not the header is defined.
Links
header() ¶ public
header(string $name): string|nullRead an HTTP header from the Request information.
If the header is not defined in the request, this method will fallback to reading data from $_SERVER and $_ENV. This fallback behavior is deprecated, and will be removed in 4.0.0
Parameters
- 
                string$name
- Name of the header you want. 
Returns
string|nullEither null on no header being set or the value of the header.
here() ¶ public
here(bool $base = true): stringGet the value of the current requests URL. Will include the query string arguments.
Parameters
- 
                bool$base optional
- Include the base path, set to false to trim the base path off. 
Returns
stringThe current request URL including query string args.
input() ¶ public
input(string|null $callback = null, array ...$args): stringRead 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.
Parameters
- 
                string|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. 
- 
                array...$args
- The additional arguments 
Returns
stringThe decoded/processed request data.
is() ¶ public
is(string|array $type, array ...$args): boolCheck 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().
Parameters
- 
                string|array$type
- The type of request you want to check. If an array this method will return true if the request matches any type. 
- 
                array...$args
- List of arguments 
Returns
boolWhether or not the request is the type you are checking.
isAll() ¶ public
isAll(array $types): boolCheck 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.
Parameters
- 
                array$types
- The types to check. 
Returns
boolSuccess.
See Also
method() ¶ public
method(): stringGet the HTTP method used for this request.
Returns
stringThe name of the HTTP method used.
normalizeHeaderName() ¶ protected
normalizeHeaderName(string $name): stringNormalize a header name into the SERVER version.
Parameters
- 
                string$name
- The header name. 
Returns
stringThe normalized header name.
offsetExists() ¶ public
offsetExists(string $name): boolArray access isset() implementation
Parameters
- 
                string$name
- thing to check. 
Returns
booloffsetGet() ¶ public
offsetGet(string $name): mixedArray access read implementation
Parameters
- 
                string$name
- Name of the key being accessed. 
Returns
mixedoffsetSet() ¶ public
offsetSet(string $name, mixed $value): voidArray access write implementation
Parameters
- 
                string$name
- Name of the key being written 
- 
                mixed$value
- The value being written. 
Returns
voidoffsetUnset() ¶ public
offsetUnset(string $name): voidArray access unset() implementation
Parameters
- 
                string$name
- Name to unset. 
Returns
voidparam() ¶ public
param(string $name, mixed ...$args): mixed|$thisSafely access the values in $this->params.
Parameters
- 
                string$name
- The name of the parameter to get. 
- 
                mixed...$args
- Value to set (deprecated). 
Returns
mixed|$thisThe value of the provided parameter. Will return false if the parameter doesn't exist or is falsey.
parseAccept() ¶ public
parseAccept(): arrayParse 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.
Returns
arrayAn array of prefValue => [content/types]
query() ¶ public
query(string|null $name = null): string|array|nullProvides a read accessor for $this->query.
Allows you to use a Hash::get() compatible syntax for reading post data.
Parameters
- 
                string|null$name optional
- Query string variable name or null to read all. 
Returns
string|array|nullThe value being read
referer() ¶ public
referer(bool $local = false): stringReturns the referer that referred this request.
Parameters
- 
                bool$local optional
- Attempt to return a local address. Local addresses do not contain hostnames. 
Returns
stringThe referring address for this request.
scheme() ¶ public
scheme(): stringGet the current url scheme used for the request.
e.g. 'http', or 'https'
Returns
stringThe scheme used for the request.
session() ¶ public
session(Cake\Http\Session|null $session = null): Cake\Http\SessionReturns the instance of the Session object for this request
If a session object is passed as first argument it will be set as the session to use for this request
Parameters
- 
                Cake\Http\Session|null$session optional
- the session object to use 
Returns
Cake\Http\SessionsetInput() ¶ public
setInput(string $input): voidModify data originally from php://input. Useful for altering json/xml data
in middleware or DispatcherFilters before it gets to RequestHandlerComponent
Parameters
- 
                string$input
- A string to replace original parsed data from input() 
Returns
voidsetTrustedProxies() ¶ public
setTrustedProxies(array $proxies): voidregister trusted proxies
Parameters
- 
                array$proxies
- ips list of trusted proxies 
Returns
voidsubdomains() ¶ public
subdomains(int $tldLength = 1): arrayGet the subdomains for a host.
Parameters
- 
                int$tldLength optional
- Number of segments your tld contains. For example: - example.comcontains 1 tld. While- example.co.ukcontains 2.
Returns
arrayAn array of subdomains.
validateUploadedFiles() ¶ protected
validateUploadedFiles(array $uploadedFiles, string $path): voidRecursively validate uploaded file data.
Parameters
- 
                array$uploadedFiles
- The new files array to validate. 
- 
                string$path
- The path thus far. 
Returns
voidThrows
InvalidArgumentExceptionIf any leaf elements are not valid files.
withAddedHeader() ¶ public
withAddedHeader(string $name, string|string[] $value): staticGet a modified request with the provided header.
Existing header values will be retained. The provided value will be appended into the existing values.
Parameters
- 
                string$name
- The header name. 
- 
                string|string[]$value
- The header value 
Returns
staticLinks
withAttribute() ¶ public
withAttribute(string $name, mixed $value): staticReturn an instance with the specified 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.
Parameters
- 
                string$name
- The attribute name. 
- 
                mixed$value
- The value of the attribute. 
Returns
staticwithBody() ¶ public
withBody(StreamInterface $body): staticReturn 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.
Parameters
- 
                StreamInterface$body
- The new request body 
Returns
staticwithCookieCollection() ¶ public
withCookieCollection(Cake\Http\Cookie\CookieCollection $cookies): staticReplace the cookies in the request with those contained in the provided CookieCollection.
Parameters
- 
                Cake\Http\Cookie\CookieCollection$cookies
- The cookie collection 
Returns
staticwithCookieParams() ¶ public
withCookieParams(array $cookies): staticReplace the cookies and get a new request instance.
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.
Parameters
- 
                array$cookies
- The new cookie data to use. 
Returns
staticwithData() ¶ public
withData(string $name, mixed $value): staticUpdate 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.
Parameters
- 
                string$name
- The dot separated path to insert $value at. 
- 
                mixed$value
- The value to insert into the request data. 
Returns
staticwithEnv() ¶ public
withEnv(string $key, string $value): staticUpdate 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.
Parameters
- 
                string$key
- The key you want to write to. 
- 
                string$value
- Value to set 
Returns
staticwithHeader() ¶ public
withHeader(string $name, string|string[] $value): staticGet a modified request with the provided 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.
Parameters
- 
                string$name
- The header name. 
- 
                string|string[]$value
- The header value 
Returns
staticLinks
withMethod() ¶ public
withMethod(string $method): staticUpdate the request method and get a new instance.
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.
Parameters
- 
                string$method
- The HTTP method to use. 
Returns
staticA new instance with the updated method.
Links
withParam() ¶ public
withParam(string $name, mixed $value): staticUpdate 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.
Parameters
- 
                string$name
- The dot separated path to insert $value at. 
- 
                mixed$value
- The value to insert into the the request parameters. 
Returns
staticwithParsedBody() ¶ public
withParsedBody(null|array|object $data): staticUpdate the parsed body and get a new instance.
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.
Parameters
- 
                null|array|object$data
- The deserialized body data. This will typically be in an array or object. 
Returns
staticwithProtocolVersion() ¶ public
withProtocolVersion(string $version): staticReturn an instance with the specified HTTP protocol version.
The version string MUST contain only the HTTP version number (e.g., "1.1", "1.0").
Parameters
- 
                string$version
- HTTP protocol version 
Returns
staticwithQueryParams() ¶ public
withQueryParams(array $query): staticUpdate the query string data and get a new instance.
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.
Parameters
- 
                array$query
- The query string data to use 
Returns
staticA new instance with the updated query string data.
Links
withRequestTarget() ¶ public
withRequestTarget(string $target): staticCreate 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
Parameters
- 
                string$target
- The request target. 
Returns
staticLinks
withUploadedFiles() ¶ public
withUploadedFiles(array $files): staticUpdate the request replacing the files, and creating a new instance.
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.
Parameters
- 
                array$files
- An array of uploaded file objects. 
Returns
staticThrows
InvalidArgumentExceptionwhen $files contains an invalid object.
withUri() ¶ public
withUri(UriInterface $uri, bool $preserveHost = false): staticReturn an instance with the specified uri
Warning Replacing the Uri will not update the base, webroot,
and url attributes.
Parameters
- 
                UriInterface$uri
- The new request uri 
- 
                bool$preserveHost optional
- Whether or not the host should be retained. 
Returns
staticwithoutAttribute() ¶ public
withoutAttribute(string $name): staticReturn an instance without the specified 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.
Parameters
- 
                string$name
- The attribute name. 
Returns
staticThrows
InvalidArgumentExceptionwithoutData() ¶ public
withoutData(string $name): staticUpdate 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.
Parameters
- 
                string$name
- The dot separated path to remove. 
Returns
staticwithoutHeader() ¶ public
withoutHeader(string $name): staticGet a modified request without a provided 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.
Parameters
- 
                string$name
- The header name to remove. 
Returns
staticLinks
Property Detail
$_detectors ¶ protected static
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.
Type
array$data ¶ protected deprecated
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.
Type
null|array|object$emulatedAttributes ¶ protected
A list of propertes that emulated by the PSR7 attribute methods.
Type
array$stream ¶ protected
Request body stream. Contains php://input unless input constructor option is used.
Type
Psr\Http\Message\StreamInterface$trustProxy ¶ public
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.
Type
bool