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.
$_detectorCache protected arrayarrayis() can be modified with addDetector(). $_environment protected array$_input protected string$attributes protected array$base protected string$cookies protected array$data protected null|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 protected array$here protected string$params protected array$protocol protected string|null$query protected array$requestTarget protected string|null$session protected $stream protected Psr\Http\Message\StreamInterfaceinput constructor option is used. $trustProxy public booleanWhether 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 protected array$uploadedFiles protected array$uri protected Psr\Http\Message\UriInterface$url protected string$webroot protected stringMagic isset method allows isset/empty checks on routing parameters.
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.
Find out which content types the client accepts or check if they accept a particular type of content.
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.
Add parameters to the request's parsed parameter set. This will overwrite any existing parameters. This modifies the parameters available through $request->getParam().
Add paths to the requests' paths vars. This will overwrite any existing paths. Provides an easy way to modify, here, webroot and base.
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 read/write accessor for $this->data. Allows you to use a Hash::get() compatible syntax for reading post data.
Get/Set value from the request's environment data. Fallback to using env() if key not set in $environment property.
Provides a safe accessor for request data. Allows you to use Hash::get() compatible paths.
Get a value from the request's environment data. Fallback to using env() if the key is not set in the $environment property.
Get the HTTP method used for this request. There are a few ways to specify a method.
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.
Provides a read accessor for $this->query. Allows you to use a Hash::get() compatible syntax for reading post data.
Modify data originally from php://input. Useful for altering json/xml data in middleware or DispatcherFilters before it gets to RequestHandlerComponent
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
$name $params __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.uri The PSR7 UriInterface object. If null, one will be created.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 object$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( string $name )
Magic get method allows access to parsed routing parameters directly on the object.
Allows access to $this->params['controller'] via $this->controller
3.4.0 Accessing routing parameters through __get will removed in 4.0.0. Use getParam() instead.
$name __isset( string $name )
Magic isset method allows isset/empty checks on routing parameters.
3.4.0 Accessing routing parameters through __isset will removed in 4.0.0. Use getParam() instead.
$name __set( string $name , mixed $value )
Magic set method allows backward compatibility for former public properties
3.6.0 Public properties will be removed in 4.0.0. Use appropriate setters instead.
$name $value _acceptHeaderDetector( array $detect )
Detects if a specific accept header is present.
$detect _createUploadedFile( array $value )
Create an UploadedFile instance from a $_FILES array.
If the value represents an array of values, this method will recursively process the data.
$value _environmentDetector( array $detect )
Detects if a specific environment variable is present.
$detect _headerDetector( array $detect )
Detects if a specific header is present.
$detect _is( string $type , array $args )
Worker for the public is() function
$type $args _normalizeNestedFiles( array $files = [] )
Normalize an array of file specifications.
Loops through all nested files and returns a normalized array of UploadedFileInterface instances.
$files optional [] _paramDetector( array $detect )
Detects if a specific request parameter is present.
$detect _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.
$header _processFiles( array $post , array $files )
Process uploaded files and move things onto the post data.
$post $files _processGet( array $query , string $queryString = '' )
Process the GET parameters and move things into the object.
$query $queryString optional '' _processPost( array $data )
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.
$data _readInput( )
Read data from php://input, mocked in tests.
_setConfig( array $config )
Process the config/settings data into properties.
$config acceptLanguage( string|null $language = null )
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'); ```
$language optional null accepts( string|null $type = null )
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.
$type optional null Either an array of all the types the client accepts or a boolean if they accept the provided type.
addDetector( string $name , callable|array $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('requested', ['param' => 'requested', 'value' => 1]); 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']]
$name $callable addParams( array $params )
Add parameters to the request's parsed parameter set. This will overwrite any existing parameters. This modifies the parameters available through $request->getParam().
3.6.0 ServerRequest::addParams() is deprecated. Use withParam() or withAttribute('params') instead.
$params addPaths( array $paths )
Add paths to the requests' paths vars. This will overwrite any existing paths. Provides an easy way to modify, here, webroot and base.
withAttribute() to modify paths instead.$paths allowMethod( string|array $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.
$methods Cake\Http\Exception\MethodNotAllowedExceptionclearDetectorCache( )
Clears the instance detector cache, used by the is() function
clientIp( )
Get the IP the client is using, or says they are using.
cookie( string $key )
Read cookie data from the request's cookie data.
$key createFromGlobals( )
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.
Cake\Http\ServerRequestFactory instead.Cake\Http\ServerRequestdata( string|null $name , ... $args )
Provides a read/write accessor for $this->data. Allows you to use a Hash::get() compatible syntax for reading post data.
$request->data('Post.title'); When reading values you will get null for keys/values that do not exist.
$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.
$name $args Cake\Http\ServerRequestdomain( integer $tldLength = 1 )
Get the domain name and include $tldLength segments of the tld.
$tldLength optional 1 Number of segments your tld contains. For example: example.com contains 1 tld. While example.co.uk contains 2.
env( string $key , string|null $value = null , string|null $default = null )
Get/Set value from the request's environment data. Fallback to using env() if key not set in $environment property.
$key $value optional null $default optional null Default value when trying to retrieve an environment variable's value that does not exist. The value parameter must be null.
$this|string|null This instance if used as setter, if used as getter either the environment value, or null if the value doesn't exist.
getAttribute( string $name , mixed|null $default = null )
Read an attribute from the request, or get the default
$name $default optional null getAttributes( )
Get all the attributes in the request.
This will include the params, webroot, base, and here attributes that CakePHP provides.
getBody( )
Gets the body of the message.
getCookie( string $key , string $default = null )
Read cookie data from the request's cookie data.
$key $default optional null 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\CookieCollectiongetCookieParams( )
Get all the cookie data from the request.
getData( string|null $name = null , mixed $default = null )
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.
$name optional null $default optional null getEnv( string $key , string|null $default = null )
Get a value from the request's environment data. Fallback to using env() if the key is not set in the $environment property.
$key $default optional null Default value when trying to retrieve an environment variable's value that does not exist.
getHeader( string $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.
$name An associative array of headers and their values. If the header doesn't exist, an empty array will be returned.
getHeaderLine( string $name )
Get a single header as a string from the request.
$name 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.
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.
getParam( string $name , mixed $default = false )
Safely access the values in $this->params.
$name $default optional false $name is not set. Default false.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.
The deserialized body parameters, if any. These will typically be an array or object.
getProtocolVersion( )
Retrieves the HTTP protocol version as a string.
getQuery( string|null $name = null , mixed $default = null )
Read 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.
$value = Hash::get($request->getQueryParams(), 'Post.id', null);
$name optional null $default optional null getQueryParams( )
Get all the query parameters in accordance to the PSR-7 specifications. To read specific query values use the alternative getQuery() method.
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.
getServerParams( )
Get all the server environment parameters.
Read all of the 'environment' or 'server' data that was used to create this request.
getSession( )
Returns the instance of the Session object for this request
Cake\Http\SessiongetUploadedFile( string $path )
Get the uploaded file from a dotted path.
$path getUploadedFiles( )
Get the array of uploaded files from the request.
getUri( )
Retrieves the URI instance.
Returns a UriInterface instance representing the URI of the request.
hasHeader( string $name )
Check if a header is set in the request.
$name header( string $name )
Read 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
$name here( boolean $base = true )
Get the value of the current requests URL. Will include the query string arguments.
$base optional true input( string|null $callback , ... $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.
$callback 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.
$args is( string|array $type , ... $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().
$type The type of request you want to check. If an array this method will return true if the request matches any type.
$args 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.
$types method( )
Get the HTTP method used for this request.
normalizeHeaderName( string $name )
Normalize a header name into the SERVER version.
$name offsetExists( string $name )
Array access isset() implementation
$name ArrayAccess::offsetExists() offsetGet( string $name )
Array access read implementation
$name ArrayAccess::offsetGet() offsetSet( string $name , mixed $value )
Array access write implementation
$name $value ArrayAccess::offsetSet() offsetUnset( string $name )
Array access unset() implementation
$name ArrayAccess::offsetUnset() param( string $name , ... $args )
Safely access the values in $this->params.
$name $args Cake\Http\ServerRequest$this The value of the provided parameter. Will return false if the parameter doesn't exist or is falsey.
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.
query( string|null $name = null )
Provides a read accessor for $this->query. Allows you to use a Hash::get() compatible syntax for reading post data.
$name optional null referer( boolean $local = false )
Returns the referer that referred this request.
$local optional false Attempt to return a local address. Local addresses do not contain hostnames.
scheme( )
Get the current url scheme used for the request.
e.g. 'http', or 'https'
session( Cake\Http\Session $session = null )
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
Cake\Http\Session $session optional null Cake\Http\SessionsetInput( string $input )
Modify data originally from php://input. Useful for altering json/xml data in middleware or DispatcherFilters before it gets to RequestHandlerComponent
$input setTrustedProxies( array $proxies )
register trusted proxies
$proxies subdomains( integer $tldLength = 1 )
Get the subdomains for a host.
$tldLength optional 1 Number of segments your tld contains. For example: example.com contains 1 tld. While example.co.uk contains 2.
validateUploadedFiles( array $uploadedFiles , string $path )
Recursively validate uploaded file data.
$uploadedFiles $path withAddedHeader( string $name , string|array $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.
$name $value Cake\Http\ServerRequestwithAttribute( string $name , mixed $value )
Return an instance with the specified request attribute.
$name $value Cake\Http\ServerRequestwithBody( Psr\Http\Message\StreamInterface $body )
Return an instance with the specified message body.
$body Cake\Http\ServerRequestwithCookieCollection( Cake\Http\Cookie\CookieCollection $cookies )
Replace the cookies in the request with those contained in the provided CookieCollection.
Cake\Http\Cookie\CookieCollection $cookies Cake\Http\ServerRequestwithCookieParams( array $cookies )
Replace the cookies and get a new request instance.
$cookies Cake\Http\ServerRequestwithData( 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.
$name $value Cake\Http\ServerRequestwithEnv( 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.
$key $value Cake\Http\ServerRequestwithHeader( string $name , string|array $value )
Get a modified request with the provided header.
$name $value Cake\Http\ServerRequestwithMethod( string $method )
Update the request method and get a new instance.
$method Cake\Http\ServerRequestwithParam( 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.
$name $value Cake\Http\ServerRequestwithParsedBody( null|array|object $data )
Update the parsed body and get a new instance.
$data The deserialized body data. This will typically be in an array or object.
Cake\Http\ServerRequestwithProtocolVersion( string $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").
$version Cake\Http\ServerRequestwithQueryParams( array $query )
Update the query string data and get a new instance.
$query Cake\Http\ServerRequestwithRequestTarget( string $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
$target Cake\Http\ServerRequestwithUploadedFiles( array $files )
Update the request replacing the files, and creating a new instance.
$files Cake\Http\ServerRequestwithUri( Psr\Http\Message\UriInterface $uri , boolean $preserveHost = false )
Return an instance with the specified uri
Warning Replacing the Uri will not update the base, webroot, and url attributes.
$uri $preserveHost optional false Cake\Http\ServerRequestwithoutAttribute( string $name )
Return an instance without the specified request attribute.
$name Cake\Http\ServerRequestwithoutData( 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.
$name Cake\Http\ServerRequestwithoutHeader( string $name )
Get a modified request without a provided header.
$name Cake\Http\ServerRequestprotected static 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.
[
'get' => ['env' => 'REQUEST_METHOD', 'value' => 'GET'],
'post' => ['env' => 'REQUEST_METHOD', 'value' => 'POST'],
'put' => ['env' => 'REQUEST_METHOD', 'value' => 'PUT'],
'patch' => ['env' => 'REQUEST_METHOD', 'value' => 'PATCH'],
'delete' => ['env' => 'REQUEST_METHOD', 'value' => 'DELETE'],
'head' => ['env' => 'REQUEST_METHOD', 'value' => 'HEAD'],
'options' => ['env' => 'REQUEST_METHOD', 'value' => 'OPTIONS'],
'ssl' => ['env' => 'HTTPS', 'options' => [1, 'on']],
'ajax' => ['env' => 'HTTP_X_REQUESTED_WITH', 'value' => 'XMLHttpRequest'],
'flash' => ['env' => 'HTTP_USER_AGENT', 'pattern' => '/^(Shockwave|Adobe) Flash/'],
'requested' => ['param' => 'requested', 'value' => 1],
'json' => ['accept' => ['application/json'], 'param' => '_ext', 'value' => 'json'],
'xml' => ['accept' => ['application/xml', 'text/xml'], 'param' => '_ext', 'value' => 'xml'],
] protected string
Base URL path.
protected array
Array of cookie data.
[]
protected null|array|object
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.
[]
protected array
A list of propertes that emulated by the PSR7 attribute methods.
['session', 'webroot', 'base', 'params', 'here']
protected string
The full address to the current request
protected array
Array of parameters parsed from the URL.
[
'plugin' => null,
'controller' => null,
'action' => null,
'_ext' => null,
'pass' => []
] protected array
Array of query string arguments
[]
protected Psr\Http\Message\StreamInterface
Request body stream. Contains php://input unless input constructor option is used.
public boolean
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.
false
protected string
The URL string used for the request.
protected string
webroot path segment for the request.
'/'
© 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/3.8/class-Cake.Http.ServerRequest.html