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.
- Cake\Http\ServerRequest implements ArrayAccess, Psr\Http\Message\ServerRequestInterface
Properties summary
-
$_detectorCache
protectedInstance cache for results of is(something) callsarray
- The built in detectors used with
array
is()
can be modified withaddDetector()
. -
$_environment
protectedArray of environment data.array
-
$_input
protectedContents of php://inputstring
-
$attributes
protectedStore the additional attributes attached to the request.array
-
$base
publicBase URL path.string
-
$cookies
publicArray of cookie data.array
-
$data
publicarray
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.
-
$emulatedAttributes
protectedA list of propertes that emulated by the PSR7 attribute methods.array
-
$here
publicThe full address to the current requeststring
-
$params
publicArray of parameters parsed from the URL.array
-
$protocol
protectedThe HTTP protocol version used.string|null
-
$query
publicArray of query string argumentsarray
-
$requestTarget
protectedThe request target if overriddenstring|null
-
$session
protected -
$stream
protectedRequest body stream. Contains php://input unlessPsr\Http\Message\StreamInterface
input
constructor option is used. -
$trustProxy
publicboolean
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.
-
$uploadedFiles
protectedArray of Psr\Http\Message\UploadedFileInterface objects.array
-
$uri
protectedUri instancePsr\Http\Message\UriInterface
-
$url
publicThe URL string used for the request.string
-
$webroot
publicwebroot path segment for the request.string
Method Summary
- __call() publicMissing method handler, handles wrapping older style isAjax() type methods
- __construct() publicCreate a new request object.
- __get() publicMagic 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() 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() 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() 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() public
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 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->getParam()
. - 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() 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() publicRead cookie data from the request's cookie data.
- 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() publicGet 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.
- 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() public
Provides a safe accessor for request data. Allows you to use Hash::get() compatible paths.
- getEnv() public
Get 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() public
Get 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.
- getProtocolVersion() publicRetrieves the HTTP protocol version as a string.
- getQuery() publicRead a specific query value or dotted path.
- getQueryParams() public
Get 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
- 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() publicRead an HTTP header from the Request information.
- here() publicGet the value of the current requests URL. Will include the query string arguments.
- host() publicGet 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() publicCheck whether or not a Request is a certain type.
- isAll() publicCheck that a request matches all the given types.
- method() publicGet the HTTP method used for this request.
- normalizeHeaderName() protectedNormalize a header name into the SERVER version.
- offsetExists() publicArray access isset() implementation
- offsetGet() publicArray access read implementation
- offsetSet() publicArray access write implementation
- offsetUnset() publicArray access unset() implementation
- param() publicSafely 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() publicGet 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() publicReturns the referer that referred this request.
- scheme() publicGet the current url scheme used for the request.
- session() publicReturns 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() 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() public
Replace 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.
- withoutHeader() publicGet a modified request without a provided header.
Method Detail
__call()source public
__call( string $name , array $params )
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
mixedThrows
BadMethodCallExceptionwhen an invalid method is called.
__construct()source 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 data -
query
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. This option is deprecated and will be removed in 4.0.0 -
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
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()source public
__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
Deprecated
3.4.0 Accessing routing parameters through __get will removed in 4.0.0. Use getParam() instead.
Parameters
- string
$name
- The property being accessed.
Returns
mixedEither the value of the parameter or null.
__isset()source public
__isset( string $name )
Magic isset method allows isset/empty checks on routing parameters.
Deprecated
3.4.0 Accessing routing parameters through __isset will removed in 4.0.0. Use getParam() instead.
Parameters
- string
$name
- The property being accessed.
Returns
booleanExistence
_acceptHeaderDetector()source protected
_acceptHeaderDetector( array $detect )
Detects if a specific accept header is present.
Parameters
- array
$detect
- Detector options array.
Returns
booleanWhether or not the request is the type you are checking.
_createUploadedFile()source protected
_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.
Parameters
- array
$value
- $_FILES struct
Returns
array|Psr\Http\Message\UploadedFileInterface_environmentDetector()source protected
_environmentDetector( array $detect )
Detects if a specific environment variable is present.
Parameters
- array
$detect
- Detector options array.
Returns
booleanWhether or not the request is the type you are checking.
_headerDetector()source protected
_headerDetector( array $detect )
Detects if a specific header is present.
Parameters
- array
$detect
- Detector options array.
Returns
booleanWhether or not the request is the type you are checking.
_is()source protected
_is( string|array $type , array $args )
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
booleanWhether or not the request is the type you are checking.
_normalizeNestedFiles()source protected
_normalizeNestedFiles( array $files [] )
Normalize 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()source protected
_paramDetector( array $detect )
Detects if a specific request parameter is present.
Parameters
- array
$detect
- Detector options array.
Returns
booleanWhether or not the request is the type you are checking.
_parseAcceptWithQualifier()source protected
_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.
Parameters
- string
$header
- Header to parse.
Returns
array_processFiles()source protected
_processFiles( array $post , array $files )
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
arraymerged post + file data.
_processGet()source protected
_processGet( array $query , string $queryString '' )
Process 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()source protected
_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.
Parameters
- array
$data
- Array of post data.
Returns
array_readInput()source protected
_readInput( )
Read data from php://input, mocked in tests.
Returns
stringcontents of php://input
_setConfig()source protected
_setConfig( array $config )
Process the config/settings data into properties.
Parameters
- array
$config
- The config data to use.
acceptLanguage()source public
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'); ```
Parameters
- string|null
$language
optional null - The language to test.
Returns
array|booleanIf a $language is provided, a boolean. Otherwise the array of accepted languages.
accepts()source public
accepts( string|null $type null )
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 null - The content type to check for. Leave null to get all types a client accepts.
Returns
array|booleanEither an array of all the types the client accepts or a boolean if they accept the provided type.
addDetector()source public static
addDetector( string $name , callable|array $callable )
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.
addParams()source public
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()
.
Parameters
- array
$params
- Array of parameters to merge in
Returns
$this The current object, you can chain this method.
addPaths()source public
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.
Parameters
- array
$paths
- Array of paths to merge in
Returns
$this The current object, you can chain this method.
allowMethod()source public
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.
Parameters
- string|array
$methods
- Allowed HTTP request methods.
Returns
booleantrue
Throws
Cake\Network\Exception\MethodNotAllowedException
clearDetectorCache()source public
clearDetectorCache( )
Clears the instance detector cache, used by the is() function
clientIp()source public
clientIp( )
Get the IP the client is using, or says they are using.
Returns
stringThe client IP.
cookie()source public
cookie( string $key )
Read cookie data from the request's cookie data.
Deprecated
3.4.0 Use getCookie() instead.Parameters
- string
$key
- The key you want to read.
Returns
null|stringEither the cookie value, or null if the value doesn't exist.
createFromGlobals()source public static
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.
Deprecated
3.4.0 UseCake\Http\ServerRequestFactory
instead.Returns
Cake\Http\ServerRequest
data()source public
data( string|null $name , ... $args )
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.
Deprecated
3.4.0 Use withData() and getData() or getParsedBody() instead.Parameters
- string|null
$name
- Dot separated name of the value to read/write
- ...
$args
- $args The data to set (deprecated)
Returns
mixed|Cake\Http\ServerRequest
$this Either the value being read, or this so you can chain consecutive writes.
domain()source public
domain( integer $tldLength 1 )
Get the domain name and include $tldLength segments of the tld.
Parameters
- integer
$tldLength
optional 1 Number of segments your tld contains. For example:
example.com
contains 1 tld. Whileexample.co.uk
contains 2.
Returns
stringDomain name without subdomains.
env()source public
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.
Deprecated
3.5.0 Use getEnv()/withEnv() instead.Parameters
- string
$key
- The key you want to read/write from/to.
- string|null
$value
optional null - Value to set. Default null.
- string|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.
Returns
$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()source public
getAttribute( string $name , mixed|null $default null )
Read an attribute from the request, or get the default
Parameters
- string
$name
- The attribute name.
- mixed|null
$default
optional null - The default value if the attribute has not been set.
Returns
mixedgetAttributes()source public
getAttributes( )
Get all the attributes in the request.
This will include the params, webroot, and base attributes that CakePHP provides.
Returns
arraygetBody()source public
getBody( )
Gets the body of the message.
Returns
Psr\Http\Message\StreamInterfaceReturns the body as a stream.
getCookie()source public
getCookie( string $key , string $default null )
Read cookie data from the request's cookie data.
Parameters
- string
$key
- The key or dotted path you want to read.
- string
$default
optional null - 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()source public
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.
Returns
Cake\Http\Cookie\CookieCollection
getCookieParams()source public
getCookieParams( )
Get all the cookie data from the request.
Returns
arrayAn array of cookie data.
getData()source public
getData( string|null $name null , mixed $default null )
Provides 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 null - Dot separated name of the value to read. Or null to read all data.
- mixed
$default
optional null - The default data.
Returns
null|string|arrayThe value being read.
getEnv()source public
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.
Parameters
- string
$key
- The key you want to read from.
- string|null
$default
optional null 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()source public
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.
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.
Link
This method is part of the PSR-7 server request interface.getHeaderLine()source public
getHeaderLine( string $name )
Get a single header as a string from the request.
Parameters
- string
$name
- The header you want to get (case-insensitive)
Returns
stringHeader values collapsed into a comma separated string.
Link
This method is part of the PSR-7 server request interface.getHeaders()source public
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.
Returns
arrayAn associative array of headers and their values.
Link
This method is part of the PSR-7 server request interface.getMethod()source public
getMethod( )
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
stringThe name of the HTTP method used.
Link
This method is part of the PSR-7 server request interface.getParam()source public
getParam( string $name , mixed $default false )
Safely access the values in $this->params.
Parameters
- string
$name
- The name or dotted path to parameter.
- mixed
$default
optional false - The default value if $name is not set.
Returns
mixedgetParsedBody()source public
getParsedBody( )
Get the parsed request body data.
If the request Content-Type is either application/x-www-form-urlencoded or multipart/form-data, nd 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()source public
getProtocolVersion( )
Retrieves the HTTP protocol version as a string.
Returns
stringHTTP protocol version.
getQuery()source public
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.
PSR-7 Alternative
$value = Hash::get($request->getQueryParams(), 'Post.id', null);
Parameters
- string|null
$name
optional null - The name or dotted path to the query param or null to read all.
- mixed
$default
optional null - The default value if the named parameter is not set, and $name is not null.
Returns
null|string|arrayQuery data.
See
ServerRequest::getQueryParams()getQueryParams()source public
getQueryParams( )
Get all the query parameters in accordance to the PSR-7 specifications. To read specific query values use the alternative getQuery() method.
Returns
arrayLink
This method is part of the PSR-7 server request interface.getRequestTarget()source public
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.
Returns
stringgetServerParams()source public
getServerParams( )
Get all the server environment parameters.
Read all of the 'environment' or 'server' data that was used to create this request.
Returns
arrayLink
This method is part of the PSR-7 server request interface.getSession()source public
getSession( )
Returns the instance of the Session object for this request
Returns
Cake\Network\Session
getUploadedFile()source public
getUploadedFile( string $path )
Get 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()source public
getUploadedFiles( )
Get the array of uploaded files from the request.
Returns
arraygetUri()source public
getUri( )
Retrieves the URI instance.
Returns
Psr\Http\Message\UriInterfaceReturns a UriInterface instance representing the URI of the request.
hasHeader()source public
hasHeader( string $name )
Check if a header is set in the request.
Parameters
- string
$name
- The header you want to get (case-insensitive)
Returns
booleanWhether or not the header is defined.
Link
This method is part of the PSR-7 server request interface.header()source public
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
Deprecated
4.0.0 The automatic fallback to env() will be removed in 4.0.0, see getHeader()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()source public
here( boolean $base true )
Get the value of the current requests URL. Will include the query string arguments.
Deprecated
3.4.0 This method will be removed in 4.0.0. You should use getRequestTarget() instead.Parameters
- boolean
$base
optional true - Include the base path, set to false to trim the base path off.
Returns
stringThe current request URL including query string args.
input()source public
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.
Parameters
- string|null
$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
- $args The additional arguments
Returns
stringThe decoded/processed request data.
is()source public
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()
.
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.
- ...
$args
- $args List of arguments
Returns
booleanWhether or not the request is the type you are checking.
isAll()source public
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.
Parameters
- array
$types
- The types to check.
Returns
booleanSuccess.
See
\Cake\Http\ServerRequest::is()method()source public
method( )
Get the HTTP method used for this request.
Deprecated
3.4.0 This method will be removed in 4.0.0. Use getMethod() instead.Returns
stringThe name of the HTTP method used.
normalizeHeaderName()source protected
normalizeHeaderName( string $name )
Normalize a header name into the SERVER version.
Parameters
- string
$name
- The header name.
Returns
stringThe normalized header name.
offsetExists()source public
offsetExists( string $name )
Array access isset() implementation
Deprecated
3.4.0 The ArrayAccess methods will be removed in 4.0.0. Use getParam() instead.Parameters
- string
$name
- thing to check.
Returns
booleanImplementation of
ArrayAccess::offsetExists()
offsetGet()source public
offsetGet( string $name )
Array access read implementation
Deprecated
3.4.0 The ArrayAccess methods will be removed in 4.0.0. Use getParam(), getData() and getQuery() instead.Parameters
- string
$name
- Name of the key being accessed.
Returns
mixedImplementation of
ArrayAccess::offsetGet()
offsetSet()source public
offsetSet( string $name , mixed $value )
Array access write implementation
Deprecated
3.4.0 The ArrayAccess methods will be removed in 4.0.0. Use withParam() instead.Parameters
- string
$name
- Name of the key being written
- mixed
$value
- The value being written.
Implementation of
ArrayAccess::offsetSet()
offsetUnset()source public
offsetUnset( string $name )
Array access unset() implementation
Deprecated
3.4.0 The ArrayAccess methods will be removed in 4.0.0. Use withParam() instead.Parameters
- string
$name
- Name to unset.
Implementation of
ArrayAccess::offsetUnset()
param()source public
param( string $name , ... $args )
Safely access the values in $this->params.
Deprecated
3.4.0 Use getParam() and withParam() instead.Parameters
- string
$name
- The name of the parameter to get.
- ...
$args
- $args Value to set (deprecated).
Returns
mixed|Cake\Http\ServerRequest
$this The value of the provided parameter. Will return false if the parameter doesn't exist or is falsey.
parseAccept()source public
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.
Returns
arrayAn array of prefValue => [content/types]
query()source public
query( string|null $name null )
Provides a read accessor for $this->query
. Allows you to use a syntax similar to CakeSession
for reading URL query data.
Deprecated
3.4.0 Use getQuery() or the PSR-7 getQueryParams() and withQueryParams() methods instead.Parameters
- string|null
$name
optional null - Query string variable name or null to read all.
Returns
string|array|nullThe value being read
referer()source public
referer( boolean $local false )
Returns the referer that referred this request.
Parameters
- boolean
$local
optional false Attempt to return a local address. Local addresses do not contain hostnames.
Returns
stringThe referring address for this request.
scheme()source public
scheme( )
Get the current url scheme used for the request.
e.g. 'http', or 'https'
Returns
stringThe scheme used for the request.
session()source public
session( Cake\Network\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
Deprecated
3.5.0 Use getSession() instead. The setter part will be removed.Parameters
-
Cake\Network\Session
$session
optional null - the session object to use
Returns
Cake\Network\Session
setInput()source public
setInput( string $input )
Modify data originally from php://input
. Useful for altering json/xml data in middleware or DispatcherFilters before it gets to RequestHandlerComponent
Deprecated
3.4.0 This method will be removed in 4.0.0. Use withBody() instead.Parameters
- string
$input
- A string to replace original parsed data from input()
subdomains()source public
subdomains( integer $tldLength 1 )
Get the subdomains for a host.
Parameters
- integer
$tldLength
optional 1 Number of segments your tld contains. For example:
example.com
contains 1 tld. Whileexample.co.uk
contains 2.
Returns
arrayAn array of subdomains.
validateUploadedFiles()source protected
validateUploadedFiles( array $uploadedFiles , string $path )
Recursively validate uploaded file data.
Parameters
- array
$uploadedFiles
- The new files array to validate.
- string
$path
- The path thus far.
Throws
InvalidArgumentExceptionIf any leaf elements are not valid files.
withAddedHeader()source public
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.
Parameters
- string
$name
- The header name.
- string|array
$value
- The header value
Returns
Cake\Http\ServerRequest
Link
This method is part of the PSR-7 server request interface.withAttribute()source public
withAttribute( string $name , mixed $value )
Return an instance with the specified request attribute.
Parameters
- string
$name
- The attribute name.
- mixed
$value
- The value of the attribute.
Returns
Cake\Http\ServerRequest
withBody()source public
withBody( Psr\Http\Message\StreamInterface $body )
Return an instance with the specified message body.
Parameters
- Psr\Http\Message\StreamInterface
$body
- The new request body
Returns
Cake\Http\ServerRequest
withCookieCollection()source public
withCookieCollection( Cake\Http\Cookie\CookieCollection $cookies )
Replace the cookies in the request with those contained in the provided CookieCollection.
Parameters
-
Cake\Http\Cookie\CookieCollection
$cookies
- The cookie collection
Returns
Cake\Http\ServerRequest
withCookieParams()source public
withCookieParams( array $cookies )
Replace the cookies and get a new request instance.
Parameters
- array
$cookies
- The new cookie data to use.
Returns
Cake\Http\ServerRequest
withData()source public
withData( string $name , mixed $value )
Update the request with a new request data element.
Returns an updated request object. This method returns a new request object and does not mutate the request in-place.
Parameters
- string
$name
- The dot separated path to insert $value at.
- mixed
$value
- The value to insert into the request data.
Returns
Cake\Http\ServerRequest
withEnv()source public
withEnv( string $key , string $value )
Update the request with a new environment data element.
Returns an updated request object. This method returns a new request object and does not mutate the request in-place.
Parameters
- string
$key
- The key you want to write to.
- string
$value
- Value to set
Returns
Cake\Http\ServerRequest
withHeader()source public
withHeader( string $name , string|array $value )
Get a modified request with the provided header.
Parameters
- string
$name
- The header name.
- string|array
$value
- The header value
Returns
Cake\Http\ServerRequest
Link
This method is part of the PSR-7 server request interface.withMethod()source public
withMethod( string $method )
Update the request method and get a new instance.
Parameters
- string
$method
- The HTTP method to use.
Returns
Cake\Http\ServerRequest
A new instance with the updated method.
Link
This method is part of the PSR-7 server request interface.withParam()source public
withParam( string $name , mixed $value )
Update the request with a new routing parameter
Returns an updated request object. This method returns a new request object and does not mutate the request in-place.
Parameters
- string
$name
- The dot separated path to insert $value at.
- mixed
$value
- The value to insert into the the request parameters.
Returns
Cake\Http\ServerRequest
withParsedBody()source public
withParsedBody( null|array|object $data )
Update the parsed body and get a new instance.
Parameters
- null|array|object
$data
The deserialized body data. This will typically be in an array or object.
Returns
Cake\Http\ServerRequest
withProtocolVersion()source public
withProtocolVersion( 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").
Parameters
- string
$version
- HTTP protocol version
Returns
Cake\Http\ServerRequest
withQueryParams()source public
withQueryParams( array $query )
Update the query string data and get a new instance.
Parameters
- array
$query
- The query string data to use
Returns
Cake\Http\ServerRequest
A new instance with the updated query string data.
Link
This method is part of the PSR-7 server request interface.withRequestTarget()source public
withRequestTarget( 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
Parameters
- string
$target
- The request target.
Returns
Cake\Http\ServerRequest
Link
(for the various request-target forms allowed in request messages)withUploadedFiles()source public
withUploadedFiles( array $files )
Update the request replacing the files, and creating a new instance.
Parameters
- array
$files
- An array of uploaded file objects.
Returns
Cake\Http\ServerRequest
Throws
InvalidArgumentExceptionwhen $files contains an invalid object.
withUri()source public
withUri( 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.
Parameters
- Psr\Http\Message\UriInterface
$uri
- The new request uri
- boolean
$preserveHost
optional false - Whether or not the host should be retained.
Returns
Cake\Http\ServerRequest
withoutAttribute()source public
withoutAttribute( string $name )
Return an instance without the specified request attribute.
Parameters
- string
$name
- The attribute name.
Returns
Cake\Http\ServerRequest
Throws
InvalidArgumentExceptionwithoutHeader()source public
withoutHeader( string $name )
Get a modified request without a provided header.
Parameters
- string
$name
- The header name to remove.
Returns
Cake\Http\ServerRequest
Link
This method is part of the PSR-7 server request interface.Properties detail
$_detectorssource
protected 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'], ]
$basesource
public string
Base URL path.
Deprecated
3.4.0 This public property will be removed in 4.0.0. Use getAttribute('base') instead.$cookiessource
public array
Array of cookie data.
Deprecated
3.4.0 This public property will be removed in 4.0.0. Use getCookie() instead.[]
$datasource
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.
Deprecated
3.4.0 This public property will be removed in 4.0.0. Use getData() instead.[]
$emulatedAttributessource
protected array
A list of propertes that emulated by the PSR7 attribute methods.
['session', 'webroot', 'base', 'params']
$heresource
public string
The full address to the current request
Deprecated
3.4.0 This public property will be removed in 4.0.0. Use getUri()->getPath() instead.$paramssource
public array
Array of parameters parsed from the URL.
Deprecated
3.4.0 This public property will be removed in 4.0.0. Use getParam() instead.[ 'plugin' => null, 'controller' => null, 'action' => null, '_ext' => null, 'pass' => [] ]
$querysource
public array
Array of query string arguments
Deprecated
3.4.0 This public property will be removed in 4.0.0. Use getQuery() or getQueryParams() instead.[]
$streamsource
protected Psr\Http\Message\StreamInterface
Request body stream. Contains php://input unless input
constructor option is used.
$trustProxysource
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
$webrootsource
public string
webroot path segment for the request.
Deprecated
3.4.0 This public property will be removed in 4.0.0. Use getAttribute('webroot') instead.'/'
© 2005–2017 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.4/class-Cake.Http.ServerRequest.html