Class Request
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.
Has both an Array and Object interface. You can access framework parameters using indexes:
$request['controller']
or $request->controller
.
Property Summary
-
$_detectorCache protected
array
Instance cache for results of is(something) calls
-
$_detectors protected static
array
The built in detectors used with
is()
can be modified withaddDetector()
. -
$_environment protected
array
Array of environment data.
-
$_input protected
string
Copy of php://input. Since this stream can only be read once in most SAPI's keep a copy of it so users don't need to know about that detail.
-
$_session protected
Cake\Network\Session
Instance of a Session object relative to this request
-
$base public
string
Base URL path.
-
$cookies public
array
Array of cookie data.
-
$data public
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.
-
$here public
string
The full address to the current request
-
$params public
array
Array of parameters parsed from the URL.
-
$query public
array
Array of querystring arguments
-
$trustProxy public
bool
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.
-
$url public
string
The URL string used for the request.
-
$webroot public
string
webroot path segment for the request.
Method Summary
-
__call() public
Missing method handler, handles wrapping older style isAjax() type methods
-
__construct() public
Create a new request object.
-
__get() public
Magic get method allows access to parsed routing parameters directly on the object.
-
__isset() public
Magic isset method allows isset/empty checks on routing parameters.
-
_acceptHeaderDetector() protected
Detects if a specific accept header is present.
-
_base() protected static
Returns a base URL and sets the proper webroot
-
_environmentDetector() protected
Detects if a specific environment variable is present.
-
_headerDetector() protected
Detects if a specific header is present.
-
_is() protected
Worker for the public is() function
-
_paramDetector() protected
Detects if a specific request parameter is present.
-
_parseAcceptWithQualifier() protected
Parse Accept* headers with qualifier options.
-
_processFileData() protected
Recursively walks the FILES array restructuring the data into something sane and usable.
-
_processFiles() protected
Process uploaded files and move things onto the post data.
-
_processGet() protected
Process the GET parameters and move things into the object.
-
_processPost() protected
Sets 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() protected
Read data from php://input, mocked in tests.
-
_setConfig() protected
Process the config/settings data into properties.
-
_url() protected static
Get the request uri. Looks in PATH_INFO first, as this is the exact value we need prepared by PHP. Following that, REQUEST_URI, PHP_SELF, HTTP_X_REWRITE_URL and argv are checked in that order. Each of these server variables have the base path, and query strings stripped off
-
acceptLanguage() public
Get the languages accepted by the client, or check if a specific language is accepted.
-
accepts() public
Find out which content types the client accepts or check if they accept a particular type of content.
-
addDetector() public static
Add 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
Add parameters to the request's parsed parameter set. This will overwrite any existing parameters. This modifies the parameters available through
$request->params
. -
addPaths() public
Add paths to the requests' paths vars. This will overwrite any existing paths. Provides an easy way to modify, here, webroot and base.
-
allowMethod() public
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.
-
clearDetectorCache() public
Clears the instance detector cache, used by the is() function
-
clientIp() public
Get the IP the client is using, or says they are using.
-
contentType() public
Get the content type used in this request.
-
cookie() public
Read cookie data from the request's cookie data.
-
createFromGlobals() public static
Wrapper method to create a new request from PHP superglobals.
-
data() public
Provides a read/write accessor for
$this->data
. Allows you to use a syntax similar toCake\Model\Datasource\Session
for reading post data. -
domain() public
Get the domain name and include $tldLength segments of the tld.
-
env() public
Get/Set value from the request's environment data. Fallback to using env() if key not set in $environment property.
-
header() public
Read an HTTP header from the Request information.
-
here() public
Get the value of the current requests URL. Will include querystring arguments.
-
host() public
Get the host that the request was handled on.
-
input() public
Read data from
php://input
. Useful when interacting with XML or JSON request body content. -
is() public
Check whether or not a Request is a certain type.
-
isAll() public
Check that a request matches all the given types.
-
method() public
Get the HTTP method used for this request. There are a few ways to specify a method.
-
offsetExists() public
Array access isset() implementation
-
offsetGet() public
Array access read implementation
-
offsetSet() public
Array access write implementation
-
offsetUnset() public
Array access unset() implementation
-
param() public
Safely access the values in $this->params.
-
parseAccept() public
Parse the HTTP_ACCEPT header and return a sorted array with content types as the keys, and pref values as the values.
-
port() public
Get the port the request was handled on.
-
query() public
Provides a read accessor for
$this->query
. Allows you to use a syntax similar toCakeSession
for reading URL query data. -
referer() public
Returns the referer that referred this request.
-
scheme() public
Get the current url scheme used for the request.
-
session() public
Returns the instance of the Session object for this request
-
setInput() public
Modify data originally from
php://input
. Useful for altering json/xml data in middleware or DispatcherFilters before it gets to RequestHandlerComponent -
subdomains() public
Get the subdomains for a host.
Method Detail
__call() ¶ public
__call(string $name, array $params): mixed
Missing 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
mixed
Throws
BadMethodCallException
when 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:
post
POST data or non query string dataquery
Additional data from the query string.files
Uploaded file data formatted like $_FILES.cookies
Cookies for this request.environment
$_SERVER and $_ENV data.url
The URL without the base path for the request.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 simulatingsession
An instance of a Session object requests with put, patch or delete data.
Parameters
-
string|array
$config optional An array of request data to create a request with.
__get() ¶ public
__get(string $name): mixed
Magic 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
mixed
__isset() ¶ public
__isset(string $name): bool
Magic isset method allows isset/empty checks on routing parameters.
Parameters
-
string
$name The property being accessed.
Returns
bool
_acceptHeaderDetector() ¶ protected
_acceptHeaderDetector(array $detect): bool
Detects if a specific accept header is present.
Parameters
-
array
$detect Detector options array.
Returns
bool
_base() ¶ protected static
_base(): array
Returns a base URL and sets the proper webroot
If CakePHP is called with index.php in the URL even though URL Rewriting is activated (and thus not needed) it swallows the unnecessary part from $base to prevent issue #3318.
Returns
array
_environmentDetector() ¶ protected
_environmentDetector(array $detect): bool
Detects if a specific environment variable is present.
Parameters
-
array
$detect Detector options array.
Returns
bool
_headerDetector() ¶ protected
_headerDetector(array $detect): bool
Detects if a specific header is present.
Parameters
-
array
$detect Detector options array.
Returns
bool
_is() ¶ protected
_is(string|array $type, array $args): bool
Worker for the public is() function
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 Array of custom detector arguments.
Returns
bool
_paramDetector() ¶ protected
_paramDetector(array $detect): bool
Detects if a specific request parameter is present.
Parameters
-
array
$detect Detector options array.
Returns
bool
_parseAcceptWithQualifier() ¶ protected
_parseAcceptWithQualifier(string $header): array
Parse 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
_processFileData() ¶ protected
_processFileData(array $data, array $post, string $path = '', string $field = ''): array
Recursively walks the FILES array restructuring the data into something sane and usable.
Parameters
-
array
$data The data being built
-
array
$post The post data being traversed
-
string
$path optional The dot separated path to insert $data into.
-
string
$field optional The terminal field in the path. This is one of the $_FILES properties e.g. name, tmp_name, size, error
Returns
array
_processFiles() ¶ protected
_processFiles(array $post, array $files): array
Process 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
array
_processGet() ¶ protected
_processGet(array $query): array
Process the GET parameters and move things into the object.
Parameters
-
array
$query The array to which the parsed keys/values are being added.
Returns
array
_processPost() ¶ protected
_processPost(array $data): array
Sets 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(): string
Read data from php://input, mocked in tests.
Returns
string
_setConfig() ¶ protected
_setConfig(array $config): void
Process the config/settings data into properties.
Parameters
-
array
$config The config data to use.
Returns
void
_url() ¶ protected static
_url(array $config): string
Get the request uri. Looks in PATH_INFO first, as this is the exact value we need prepared by PHP. Following that, REQUEST_URI, PHP_SELF, HTTP_X_REWRITE_URL and argv are checked in that order. Each of these server variables have the base path, and query strings stripped off
Parameters
-
array
$config Configuration to set.
Returns
string
acceptLanguage() ¶ public
acceptLanguage(string|null $language = null): array|bool
Get the languages accepted by the client, or check if a specific language is accepted.
Get the list of accepted languages:
\Cake\Network\Request::acceptLanguage();
Check if a specific language is accepted:
\Cake\Network\Request::acceptLanguage('es-es');
Parameters
-
string|null
$language optional The language to test.
Returns
array|bool
accepts() ¶ public
accepts(string|null $type = null): array|bool
Find 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|bool
addDetector() ¶ public static
addDetector(string $name, callable|array $callable): void
Add 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
void
addParams() ¶ public
addParams(array $params): $this
Add parameters to the request's parsed parameter set. This will overwrite any existing parameters.
This modifies the parameters available through $request->params
.
Parameters
-
array
$params Array of parameters to merge in
Returns
$this
addPaths() ¶ public
addPaths(array $paths): $this
Add 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
$this
allowMethod() ¶ public
allowMethod(string|array $methods): bool
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.
Parameters
-
string|array
$methods Allowed HTTP request methods.
Returns
bool
Throws
Cake\Network\Exception\MethodNotAllowedException
clearDetectorCache() ¶ public
clearDetectorCache(): void
Clears the instance detector cache, used by the is() function
Returns
void
clientIp() ¶ public
clientIp(): string
Get the IP the client is using, or says they are using.
Returns
string
contentType() ¶ public
contentType(): string
Get the content type used in this request.
Returns
string
cookie() ¶ public
cookie(string $key): null|string
Read cookie data from the request's cookie data.
Parameters
-
string
$key The key you want to read.
Returns
null|string
createFromGlobals() ¶ public static
createFromGlobals(): Cake\Network\Request
Wrapper 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
Cake\Network\Request
data() ¶ public
data(string|null $name = null): mixed|$this
Provides a read/write accessor for $this->data
. Allows you
to use a syntax similar to Cake\Model\Datasource\Session
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
Returns
mixed|$this
domain() ¶ public
domain(int $tldLength = 1): string
Get the domain name and include $tldLength segments of the tld.
Parameters
-
int
$tldLength optional Number of segments your tld contains. For example:
example.com
contains 1 tld. Whileexample.co.uk
contains 2.
Returns
string
env() ¶ public
env(string $key, string|null $value = null, string|null $default = null): $this|string|null
Get/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|null
header() ¶ public
header(string $name): string|null
Read an HTTP header from the Request information.
Parameters
-
string
$name Name of the header you want.
Returns
string|null
here() ¶ public
here(bool $base = true): string
Get the value of the current requests URL. Will include querystring arguments.
Parameters
-
bool
$base optional Include the base path, set to false to trim the base path off.
Returns
string
input() ¶ public
input(string|null $callback = null): string
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.
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.
Returns
string
is() ¶ public
is(string|array $type): bool
Check whether or not a Request is a certain type.
Uses the built in detection rules as well as additional rules
defined with Cake\Network\CakeRequest::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.
Returns
bool
isAll() ¶ public
isAll(array $types): bool
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.
Parameters
-
array
$types The types to check.
Returns
bool
See Also
method() ¶ public
method(): string
Get 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
string
offsetExists() ¶ public
offsetExists(string $name): bool
Array access isset() implementation
Parameters
-
string
$name thing to check.
Returns
bool
offsetGet() ¶ public
offsetGet(string $name): mixed
Array access read implementation
Parameters
-
string
$name Name of the key being accessed.
Returns
mixed
offsetSet() ¶ public
offsetSet(string $name, mixed $value): void
Array access write implementation
Parameters
-
string
$name Name of the key being written
-
mixed
$value The value being written.
Returns
void
offsetUnset() ¶ public
offsetUnset(string $name): void
Array access unset() implementation
Parameters
-
string
$name Name to unset.
Returns
void
param() ¶ public
param(string $name): mixed|$this
Safely access the values in $this->params.
Parameters
-
string
$name The name of the parameter to get.
Returns
mixed|$this
parseAccept() ¶ public
parseAccept(): array
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\Network\Request::accept() to get a simple list of the accepted content types.
Returns
array
query() ¶ public
query(string $name): mixed
Provides a read accessor for $this->query
. Allows you
to use a syntax similar to CakeSession
for reading URL query data.
Parameters
-
string
$name Query string variable name
Returns
mixed
referer() ¶ public
referer(bool $local = false): string
Returns the referer that referred this request.
Parameters
-
bool
$local optional Attempt to return a local address. Local addresses do not contain hostnames.
Returns
string
scheme() ¶ public
scheme(): string
Get the current url scheme used for the request.
e.g. 'http', or 'https'
Returns
string
session() ¶ public
session(Cake\Network\Session|null $session = null): Cake\Network\Session
Returns 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\Network\Session|null
$session optional the session object to use
Returns
Cake\Network\Session
setInput() ¶ public
setInput(string $input): void
Modify 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
void
subdomains() ¶ public
subdomains(int $tldLength = 1): array
Get the subdomains for a host.
Parameters
-
int
$tldLength optional Number of segments your tld contains. For example:
example.com
contains 1 tld. Whileexample.co.uk
contains 2.
Returns
array
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\Network\Request::addDetector() for the various formats and ways to define detectors.
Type
array
$_input ¶ protected
Copy of php://input. Since this stream can only be read once in most SAPI's keep a copy of it so users don't need to know about that detail.
Type
string
$_session ¶ protected
Instance of a Session object relative to this request
Type
Cake\Network\Session
$data ¶ public
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
array
$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