Request
API reference › yii › web › Request
The web Request class represents an HTTP request.
It encapsulates the $_SERVER variable and resolves its inconsistency among different Web servers. Also it provides an interface to retrieve request parameters from $_POST, $_GET, $_COOKIES and REST parameters sent via other HTTP methods like PUT or DELETE.
Request is configured as an application component in Application by default.
You can access that instance via Yii::$app->request.
For more details and usage information on Request, see the guide article on requests.
Properties
Section titled “Properties”| Property | Type | Description | Defined by |
|---|---|---|---|
$absoluteUrl read-only | string | The currently requested absolute URL. | Request |
$acceptableContentTypes | array | The content types ordered by the quality score. | Request |
$acceptableLanguages | array | The languages ordered by the preference level. | Request |
$authCredentials read-only | array | That contains exactly two elements: - 0: the username sent via HTTP authentication, null if the username is not given - 1: the password sent via HTTP authentication, null if the password is not given. | Request |
$authPassword read-only | string| | The password sent via HTTP authentication, null if the password is not given. | Request |
$authUser read-only | string| | The username sent via HTTP authentication, null if the username is not given. | Request |
$baseUrl | string | The relative URL for the application. | Request |
$behaviors read-only | array<yii\<static>> | List of behaviors attached to this component. | yii\ |
$bodyParams | mixed | The request parameters given in the request body. | Request |
$contentType read-only | string | Request content-type. | Request |
$cookies read-only | CookieCollection | The cookie collection. | Request |
$cookieValidationKey | string | A secret key used for cookie validation. Default: null. | Request |
$csrfCookie | array | The configuration for creating the CSRF cookie. Default: ['httpOnly' => true]. | Request |
$csrfHeader | string | The name of the HTTP header for sending CSRF token. Default: self::CSRF_HEADER. | Request |
$csrfHeaderUnsafeMethods | array | “unsafe” methods not triggered a CORS-preflight request This property is used only when both $enableCsrfValidation and $validateCsrfHeaderOnly are true. Default: ['GET',. | Request |
$csrfParam | string | The name of the token used to prevent CSRF. Default: '_csrf'. | Request |
$csrfToken read-only | null| | The token used to perform CSRF validation. | Request |
$csrfTokenFromHeader read-only | string| | The CSRF token sent via $csrfHeader by browser. | Request |
$csrfTokenSafeMethods | array | The name of the HTTP header for sending CSRF token. by default validate CSRF token on non-”safe” methods only This property is used only when $enableCsrfValidation is true. Default: ['GET',. | Request |
$enableCookieValidation | bool | Whether cookies should be validated to ensure they are not tampered. Default: true. | Request |
$enableCsrfCookie | bool | Whether to use cookie to persist CSRF token. Default: true. | Request |
$enableCsrfValidation | bool | Whether to enable CSRF (Cross-Site Request Forgery) validation. Default: true. | Request |
$eTags read-only | array | The entity tags. | Request |
$headers read-only | HeaderCollection | The header collection. | Request |
$hostInfo | string| | Schema and hostname part (with port number if needed) of the request URL (e.g. https://www.yiiframework.com), null if can’t be obtained from $_SERVER and wasn’t set. | Request |
$hostName read-only | string| | Hostname part of the request URL (e.g. www.yiiframework.com). | Request |
$ipHeaders | string[] | List of headers where proxies store the real client IP. Default: ['X-Forwarded-For']. Available since 2.0.13. | Request |
$isAjax read-only | bool | Whether this is an AJAX (XMLHttpRequest) request. | Request |
$isConsoleRequest | bool | The value indicating whether the current request is made via console. | yii\ |
$isDelete read-only | bool | Whether this is a DELETE request. | Request |
$isFlash read-only | bool | Whether this is an Adobe Flash or Adobe Flex request. | Request |
$isGet read-only | bool | Whether this is a GET request. | Request |
$isHead read-only | bool | Whether this is a HEAD request. | Request |
$isOptions read-only | bool | Whether this is a OPTIONS request. | Request |
$isPatch read-only | bool | Whether this is a PATCH request. | Request |
$isPjax read-only | bool | Whether this is a PJAX request. | Request |
$isPost read-only | bool | Whether this is a POST request. | Request |
$isPut read-only | bool | Whether this is a PUT request. | Request |
$isSecureConnection read-only | bool | If the request is sent via secure channel (https). | Request |
$method read-only | string | Request method, such as GET, POST, HEAD, PUT, PATCH, DELETE. | Request |
$methodParam | string | The name of the POST parameter that is used to indicate if a request is a PUT, PATCH or DELETE request tunneled through POST. Default: '_method'. | Request |
$origin read-only | string| | URL origin of a CORS request, null if not available. | Request |
$parsers | array | The parsers for converting the raw HTTP request body into $bodyParams. Default: []. | Request |
$pathInfo | string | Part of the request URL that is after the entry script and before the question mark. | Request |
$port | int | Port number for insecure requests. | Request |
$portHeaders | string[] | List of headers where proxies store the real request port. Default: ['X-Forwarded-Port']. Available since 2.0.46. | Request |
$preferredLanguage read-only | string | The language that the application should use. | Request |
$queryParams | array | The request GET parameter values. | Request |
$queryString read-only | string | Part of the request URL that is after the question mark. | Request |
$rawBody | string | The request body. | Request |
$referrer read-only | string| | URL referrer, null if not available. | Request |
$remoteHost read-only | string| | Remote host name, null if not available. | Request |
$remoteIP read-only | string| | Remote IP address, null if not available. | Request |
$scriptFile | string | The entry script file path. | Request |
$scriptUrl | string | The relative URL of the entry script. | Request |
$secureHeaders | array | Lists of headers that are, by default, subject to the trusted host configuration. Default: ['X-Forwarded-For',. Available since 2.0.13. | Request |
$securePort | int | Port number for secure requests. | Request |
$secureProtocolHeaders | array | List of headers to check for determining whether the connection is made via HTTPS. Default: ['X-Forwarded-Proto' => ['https'],. Available since 2.0.13. | Request |
$serverName read-only | string| | Server name, null if not available. | Request |
$serverPort read-only | int| | Server port number, null if not available. | Request |
$trustedHosts | array | The configuration for trusted security related headers. Default: []. Available since 2.0.13. | Request |
$url | string | The currently requested relative URL. | Request |
$userAgent read-only | string| | User agent, null if not available. | Request |
$userHost read-only | string| | User host name, null if not available. | Request |
$userIP read-only | string| | User IP address, null if not available. | Request |
$validateCsrfHeaderOnly | bool | Whether to use custom header only to CSRF validation of SPA. Default: false. | Request |
Methods
Section titled “Methods”| Method | Description | Defined by |
|---|---|---|
__construct() | Constructor. | yii\ |
__call() | Calls the named method which is not a class method. | yii\ |
__clone() | This method is called after the object is created by cloning an existing one. | yii\ |
__get() | Returns the value of a component property. | yii\ |
__isset() | Checks if a property is set, i.e. defined and not null. | yii\ |
__set() | Sets the value of a component property. | yii\ |
__unset() | Sets a component property to be null. | yii\ |
attachBehavior() | Attaches a behavior to this component. | yii\ |
attachBehaviors() | Attaches a list of behaviors to the component. | yii\ |
behaviors() | Returns a list of behaviors that this component should behave as. | yii\ |
canGetProperty() | Returns a value indicating whether a property can be read. | yii\ |
canSetProperty() | Returns a value indicating whether a property can be set. | yii\ |
className() static | Returns the fully qualified name of this class. | yii\ |
detachBehavior() | Detaches a behavior from the component. | yii\ |
detachBehaviors() | Detaches all behaviors from the component. | yii\ |
ensureBehaviors() | Makes sure that the behaviors declared in behaviors() are attached to this component. | yii\ |
get() | Returns GET parameter with a given name. If name isn’t specified, returns an array of all GET parameters. | Request |
getAbsoluteUrl() | Returns the currently requested absolute URL. | Request |
getAcceptableContentTypes() | Returns the content types acceptable by the end user. | Request |
getAcceptableLanguages() | Returns the languages acceptable by the end user. | Request |
getAuthCredentials() | Request | |
getAuthPassword() | Request | |
getAuthUser() | Request | |
getBaseUrl() | Returns the relative URL for the application. | Request |
getBehavior() | Returns the named behavior object. | yii\ |
getBehaviors() | Returns all behaviors attached to this component. | yii\ |
getBodyParam() | Returns the named request body parameter value. | Request |
getBodyParams() | Returns the request parameters given in the request body. | Request |
getContentType() | Returns request content-type The Content-Type header field indicates the MIME type of the data contained in getRawBody() or, in the case of the HEAD method, the media type that would have been sent had the request been a GET. | Request |
getCookies() | Returns the cookie collection. | Request |
getCsrfToken() | Returns the token used to perform CSRF validation. | Request |
getCsrfTokenFromHeader() | Request | |
getETags() | Gets the Etags. | Request |
getHeaders() | Returns the header collection. | Request |
getHostInfo() | Returns the schema and host part of the current request URL. | Request |
getHostName() | Returns the host part of the current request URL. | Request |
getIsAjax() | Returns whether this is an AJAX (XMLHttpRequest) request. | Request |
getIsConsoleRequest() | Returns a value indicating whether the current request is made via command line. | yii\ |
getIsDelete() | Returns whether this is a DELETE request. | Request |
getIsFlash() | Returns whether this is an Adobe Flash or Flex request. | Request |
getIsGet() | Returns whether this is a GET request. | Request |
getIsHead() | Returns whether this is a HEAD request. | Request |
getIsOptions() | Returns whether this is an OPTIONS request. | Request |
getIsPatch() | Returns whether this is a PATCH request. | Request |
getIsPjax() | Returns whether this is a PJAX request. | Request |
getIsPost() | Returns whether this is a POST request. | Request |
getIsPut() | Returns whether this is a PUT request. | Request |
getIsSecureConnection() | Return if the request is sent via secure channel (https). | Request |
getMethod() | Returns the method of the current request (e.g. GET, POST, HEAD, PUT, PATCH, DELETE). | Request |
getOrigin() | Returns the URL origin of a CORS request. | Request |
getPathInfo() | Returns the path info of the currently requested URL. | Request |
getPort() | Returns the port to use for insecure requests. | Request |
getPreferredLanguage() | Returns the user-preferred language that should be used by this application. | Request |
getQueryParam() | Returns the named GET parameter value. | Request |
getQueryParams() | Returns the request parameters given in the $queryString. | Request |
getQueryString() | Returns part of the request URL that is after the question mark. | Request |
getRawBody() | Returns the raw HTTP request body. | Request |
getReferrer() | Returns the URL referrer. | Request |
getRemoteHost() | Returns the host name of the other end of this connection. | Request |
getRemoteIP() | Returns the IP on the other end of this connection. | Request |
getScriptFile() | Returns the entry script file path. | Request |
getScriptUrl() | Returns the relative URL of the entry script. | Request |
getSecurePort() | Returns the port to use for secure requests. | Request |
getServerName() | Returns the server name. | Request |
getServerPort() | Returns the server port number. If a port is specified via a forwarding header (e.g. ‘X-Forwarded-Port’) and the remote host is a “trusted host” the that port will be used (see $portHeaders), otherwise the default server port will be returned. | Request |
getUrl() | Returns the currently requested relative URL. | Request |
getUserAgent() | Returns the user agent. | Request |
getUserHost() | Returns the user host name. | Request |
getUserIP() | Returns the user IP address. | Request |
hasEventHandlers() | Returns a value indicating whether there is any handler attached to the named event. | yii\ |
hasMethod() | Returns a value indicating whether a method is defined. | yii\ |
hasProperty() | Returns a value indicating whether a property is defined for this component. | yii\ |
init() | Initializes the object. | yii\ |
off() | Detaches an existing event handler from this component. | yii\ |
on() | Attaches an event handler to an event. | yii\ |
parseAcceptHeader() | Parses the given Accept (or Accept-Language) header. | Request |
post() | Returns POST parameter with a given name. If name isn’t specified, returns an array of all POST parameters. | Request |
resolve() | Resolves the current request into a route and the associated parameters. | Request |
setAcceptableContentTypes() | Sets the acceptable content types. | Request |
setAcceptableLanguages() | Request | |
setBaseUrl() | Sets the relative URL for the application. | Request |
setBodyParams() | Sets the request body parameters. | Request |
setHostInfo() | Sets the schema and host part of the application URL. | Request |
setIsConsoleRequest() | Sets the value indicating whether the current request is made via command line. | yii\ |
setPathInfo() | Sets the path info of the current request. | Request |
setPort() | Sets the port to use for insecure requests. | Request |
setQueryParams() | Sets the request $queryString parameters. | Request |
setRawBody() | Sets the raw HTTP request body, this method is mainly used by test scripts to simulate raw HTTP requests. | Request |
setScriptFile() | Sets the entry script file path. | Request |
setScriptUrl() | Sets the relative URL for the application entry script. | Request |
setSecurePort() | Sets the port to use for secure requests. | Request |
setUrl() | Sets the currently requested relative URL. | Request |
trigger() | Triggers an event. | yii\ |
validateCsrfToken() | Performs the CSRF validation. | Request |
createCsrfCookie() protected | Creates a cookie with a randomly generated CSRF token. | Request |
filterHeaders() protected | Filters headers according to the $trustedHosts. | Request |
generateCsrfToken() protected | Generates an unmasked random token used to perform CSRF validation. | Request |
getIpValidator() protected | Creates instance of IpValidator. | Request |
getSecureForwardedHeaderParts() protected | Returns decoded forwarded header | Request |
getSecureForwardedHeaderTrustedPart() protected | Gets first Forwarded header value for token | Request |
getSecureForwardedHeaderTrustedParts() protected | Gets only trusted Forwarded header parts | Request |
getTrustedHeaders() protected | Trusted headers according to the $trustedHosts. | Request |
getUserIpFromIpHeader() protected | Return user IP’s from IP header. | Request |
getUserIpFromIpHeaders() protected | Returns the user IP address from $ipHeaders. | Request |
loadCookies() protected | Converts $_COOKIE into an array of Cookie. | Request |
loadCsrfToken() protected | Loads the CSRF token from cookie or session. | Request |
resolvePathInfo() protected | Resolves the path info part of the currently requested URL. | Request |
resolveRequestUri() protected | Resolves the request URI portion for the currently requested URL. | Request |
Constants
Section titled “Constants”| Constant | Value | Description | Defined by |
|---|---|---|---|
CSRF_HEADER | 'X-CSRF-Token' | Default name of the HTTP header for sending CSRF token. | Request |
Property details
Section titled “Property details”$acceptableContentTypes
Section titled “$acceptableContentTypes ”public array $acceptableContentTypesThe content types ordered by the quality score.
Types with the highest scores will be returned first. The array keys are the content types, while the array values are the corresponding quality score and other parameters as given in the header.
$acceptableLanguages
Section titled “$acceptableLanguages ”public array $acceptableLanguagesThe languages ordered by the preference level.
The first element represents the most preferred language.
$contentType
Section titled “$contentType ”public string $contentTypeRequest content-type.
Empty string is returned if this information is not available.
Access
Read-only (virtual property).
$cookieValidationKey
Section titled “$cookieValidationKey ”public string $cookieValidationKey = nullA secret key used for cookie validation.
This property must be set if $enableCookieValidation is true.
$csrfCookie
Section titled “$csrfCookie ”public array $csrfCookie = ['httpOnly' => true]The configuration for creating the CSRF cookie.
This property is used only when
both $enableCsrfValidation and $enableCsrfCookie are true.
$csrfHeader
Section titled “$csrfHeader ”public string $csrfHeader = self::CSRF_HEADERThe name of the HTTP header for sending CSRF token.
Defaults to CSRF_HEADER.
This property may be changed for Yii API applications only.
Don’t change this property for Yii Web application.
$csrfParam
Section titled “$csrfParam ”public string $csrfParam = '_csrf'The name of the token used to prevent CSRF.
Defaults to ‘_csrf’.
This property is used only when $enableCsrfValidation is true.
$csrfToken
Section titled “$csrfToken ”public null|string $csrfTokenThe token used to perform CSRF validation.
Null is returned if the
$validateCsrfHeaderOnly is true.
Access
Read-only (virtual property).
$csrfTokenFromHeader
Section titled “$csrfTokenFromHeader ”public string|null $csrfTokenFromHeaderThe CSRF token sent via $csrfHeader by browser.
Null is returned if no such header is sent.
Access
Read-only (virtual property).
$enableCookieValidation
Section titled “$enableCookieValidation ”public bool $enableCookieValidation = trueWhether cookies should be validated to ensure they are not tampered.
Defaults to true.
$enableCsrfCookie
Section titled “$enableCsrfCookie ”public bool $enableCsrfCookie = trueWhether to use cookie to persist CSRF token.
If false, CSRF token will be stored
in session under the name of $csrfParam. Note that while storing CSRF tokens in session increases
security, it requires starting a session for every page, which will degrade your site performance.
$enableCsrfValidation
Section titled “$enableCsrfValidation ”public bool $enableCsrfValidation = trueWhether to enable CSRF (Cross-Site Request Forgery) validation.
Defaults to true. When CSRF validation is enabled, forms submitted to an Yii Web application must be originated from the same application. If not, a 400 HTTP exception will be raised.
Note, this feature requires that the user client accepts cookie. Also, to use this feature,
forms submitted via POST method must contain a hidden input whose name is specified by $csrfParam.
You may use Html::beginForm() to generate his hidden input.
In JavaScript, you may get the values of $csrfParam and $csrfToken via yii.getCsrfParam() and
yii.getCsrfToken(), respectively. The YiiAsset asset must be registered.
You also need to include CSRF meta tags in your pages by using Html::csrfMetaTags().
For SPA, you can use CSRF validation by custom header with a random or an empty value.
Include a header with the name specified by $csrfHeader to requests that must be validated.
Warning! CSRF validation by custom header can be used only for same-origin requests or
with CORS configured to allow requests from the list of specific origins only.
$ipHeaders
Section titled “$ipHeaders ”public string[] $ipHeaders = ['X-Forwarded-For']List of headers where proxies store the real client IP.
It’s not advisable to put insecure headers here.
To use the Forwarded header according to RFC 7239, the header must be added to $secureHeaders list.
The match of header names is case-insensitive.
Since
2.0.13
$method
Section titled “$method ”public string $methodRequest method, such as GET, POST, HEAD, PUT, PATCH, DELETE.
The value returned is turned into upper case.
Access
Read-only (virtual property).
$methodParam
Section titled “$methodParam ”public string $methodParam = '_method'The name of the POST parameter that is used to indicate if a request is a PUT, PATCH or DELETE request tunneled through POST.
Defaults to ‘_method’.
$parsers
Section titled “$parsers ”public array $parsers = []The parsers for converting the raw HTTP request body into $bodyParams.
The array keys are the request Content-Types, and the array values are the
corresponding configurations for creating the parser objects.
A parser must implement the RequestParserInterface.
To enable parsing for JSON requests you can use the JsonParser class like in the following example:
[ 'application/json' => 'yii\web\JsonParser',]To register a parser for parsing all request types you can use '*' as the array key.
This one will be used as a fallback in case no other types match.
$pathInfo
Section titled “$pathInfo ”public string $pathInfoPart of the request URL that is after the entry script and before the question mark.
Note, the returned path info is already URL-decoded.
$portHeaders
Section titled “$portHeaders ”public string[] $portHeaders = ['X-Forwarded-Port']List of headers where proxies store the real request port.
It’s not advisable to put insecure headers here.
To use the Forwarded Port, the header must be added to $secureHeaders list.
The match of header names is case-insensitive.
Since
2.0.46
$secureHeaders
Section titled “$secureHeaders ”public array $secureHeaders = ['X-Forwarded-For', 'X-Forwarded-Host', 'X-Forwarded-Proto', 'X-Forwarded-Port', 'Front-End-Https', 'X-Rewrite-Url', 'X-Original-Host']Lists of headers that are, by default, subject to the trusted host configuration.
These headers will be filtered unless explicitly allowed in $trustedHosts.
If the list contains the Forwarded header, processing will be done according to RFC 7239.
The match of header names is case-insensitive.
Since
2.0.13
$secureProtocolHeaders
Section titled “$secureProtocolHeaders ”public array $secureProtocolHeaders = ['X-Forwarded-Proto' => ['https'], 'Front-End-Https' => ['on']]List of headers to check for determining whether the connection is made via HTTPS.
The array keys are header names and the array value is a list of header values that indicate a secure connection. The match of header names and values is case-insensitive. It’s not advisable to put insecure headers here.
Since
2.0.13
$trustedHosts
Section titled “$trustedHosts ”public array $trustedHosts = []The configuration for trusted security related headers.
An array key is an IPv4 or IPv6 IP address in CIDR notation for matching a client.
An array value is a list of headers to trust. These will be matched against
$secureHeaders to determine which headers are allowed to be sent by a specified host.
The case of the header names must be the same as specified in $secureHeaders.
For example, to trust all headers listed in $secureHeaders for IP addresses
in range 192.168.0.0-192.168.0.254 write the following:
[ '192.168.0.0/24',]To trust just the X-Forwarded-For header from 10.0.0.1, use:
[ '10.0.0.1' => ['X-Forwarded-For']]Default is to trust all headers except those listed in $secureHeaders from all hosts.
Matches are tried in order and searching is stopped when IP matches.
Info: Matching is performed using
IpValidator. See IpValidator::setRanges() andIpValidator::$networksfor advanced matching.
Since
2.0.13
public string $urlThe currently requested relative URL.
Note that the URI returned may be URL-encoded depending on the client.
$validateCsrfHeaderOnly
Section titled “$validateCsrfHeaderOnly ”public bool $validateCsrfHeaderOnly = falseWhether to use custom header only to CSRF validation of SPA.
Defaults to false.
If false and $enableCsrfValidation is true, CSRF validation by token will used.
Warning! CSRF validation by custom header can be used for Yii API applications only.
Method details
Section titled “Method details”get()
Section titled “get() ”public function get(string|null $name = null, mixed $defaultValue = null): ($name is null ? array : mixed)Returns GET parameter with a given name. If name isn’t specified, returns an array of all GET parameters.
Parameters
| Parameter | Type | Description |
|---|---|---|
$name | string| | The parameter name |
$defaultValue | mixed | The default parameter value if the parameter does not exist. |
Returns
($name is null ? array : mixed)
getAbsoluteUrl()
Section titled “getAbsoluteUrl() ”public function getAbsoluteUrl(): stringReturns the currently requested absolute URL.
This is a shortcut to the concatenation of $hostInfo and $url.
Returns
string: The currently requested absolute URL.
getAcceptableContentTypes()
Section titled “getAcceptableContentTypes() ”public function getAcceptableContentTypes(): arrayReturns the content types acceptable by the end user.
This is determined by the Accept HTTP header. For example,
$_SERVER['HTTP_ACCEPT'] = 'text/plain; q=0.5, application/json; version=1.0, application/xml; version=2.0;';$types = $request->getAcceptableContentTypes();print_r($types);// displays:// [// 'application/json' => ['q' => 1, 'version' => '1.0'],// 'application/xml' => ['q' => 1, 'version' => '2.0'],// 'text/plain' => ['q' => 0.5],// ]Returns
array: The content types ordered by the quality score. Types with the highest scores will be returned first. The array keys are the content types, while the array values are the corresponding quality score and other parameters as given in the header.
getAcceptableLanguages()
Section titled “getAcceptableLanguages() ”public function getAcceptableLanguages(): arrayReturns the languages acceptable by the end user.
This is determined by the Accept-Language HTTP header.
Returns
array: The languages ordered by the preference level. The first element represents the most preferred language.
getAuthCredentials()
Section titled “getAuthCredentials() ”public function getAuthCredentials(): arrayReturns
array: That contains exactly two elements: - 0: the username sent via HTTP authentication, null if the username is not given - 1: the password sent via HTTP authentication, null if the password is not given
Since
2.0.13
See also
getAuthUser()(to get only username)getAuthPassword()(to get only password)
getAuthPassword()
Section titled “getAuthPassword() ”public function getAuthPassword(): string|nullReturns
string|null: The password sent via HTTP authentication, null if the password is not given
See also
getAuthCredentials()(to get both username and password in one call)
getAuthUser()
Section titled “getAuthUser() ”public function getAuthUser(): string|nullReturns
string|null: The username sent via HTTP authentication, null if the username is not given
See also
getAuthCredentials()(to get both username and password in one call)
getBaseUrl()
Section titled “getBaseUrl() ”public function getBaseUrl(): stringReturns the relative URL for the application.
This is similar to $scriptUrl except that it does not include the script file name,
and the ending slashes are removed.
getBodyParam()
Section titled “getBodyParam() ”public function getBodyParam(string $name, mixed $defaultValue = null): mixedReturns the named request body parameter value.
If the parameter does not exist, the second parameter passed to this method will be returned.
Parameters
| Parameter | Type | Description |
|---|---|---|
$name | string | The parameter name |
$defaultValue | mixed | The default parameter value if the parameter does not exist. |
Returns
mixed: The parameter value
See also
getBodyParams()
Section titled “getBodyParams() ”public function getBodyParams(): mixedReturns the request parameters given in the request body.
Request parameters are determined using the parsers configured in $parsers property.
If no parsers are configured for the current $contentType it uses the PHP function mb_parse_str()
to parse the request body.
Returns
mixed: The request parameters given in the request body.
Throws
yii\base\InvalidConfigException: if a registered parser does not implement theRequestParserInterface.
See also
getContentType()
Section titled “getContentType() ”public function getContentType(): stringReturns request content-type
The Content-Type header field indicates the MIME type of the data
contained in getRawBody() or, in the case of the HEAD method, the
media type that would have been sent had the request been a GET.
For the MIME-types the user expects in response, see $acceptableContentTypes.
Returns
string: Request content-type. Empty string is returned if this information is not available.
getCookies()
Section titled “getCookies() ”public function getCookies(): yii\web\CookieCollectionReturns the cookie collection.
Through the returned cookie collection, you may access a cookie using the following syntax:
$cookie = $request->cookies['name']if ($cookie !== null) { $value = $cookie->value;}
// alternatively$value = $request->cookies->getValue('name');Returns
CookieCollection: The cookie collection.
getCsrfToken()
Section titled “getCsrfToken() ”public function getCsrfToken(bool $regenerate = false): null|stringReturns the token used to perform CSRF validation.
This token is generated in a way to prevent BREACH attacks. It may be passed along via a hidden field of an HTML form or an HTTP header value to support CSRF validation.
Parameters
| Parameter | Type | Description |
|---|---|---|
$regenerate | bool | Whether to regenerate CSRF token. When this parameter is true, each time this method is called, a new CSRF token will be generated and persisted (in session or cookie). |
Returns
null|string: The token used to perform CSRF validation. Null is returned if the $validateCsrfHeaderOnly is true.
getCsrfTokenFromHeader()
Section titled “getCsrfTokenFromHeader() ”public function getCsrfTokenFromHeader(): string|nullReturns
string|null: The CSRF token sent via $csrfHeader by browser. Null is returned if no such header is sent.
getETags()
Section titled “getETags() ”public function getETags(): arrayGets the Etags.
Returns
array: The entity tags
getHeaders()
Section titled “getHeaders() ”public function getHeaders(): yii\web\HeaderCollectionReturns the header collection.
The header collection contains incoming HTTP headers.
Returns
HeaderCollection: The header collection
getHostInfo()
Section titled “getHostInfo() ”public function getHostInfo(): string|nullReturns the schema and host part of the current request URL.
The returned URL does not have an ending slash.
By default this value is based on the user request information. This method will
return the value of $_SERVER['HTTP_HOST'] if it is available or $_SERVER['SERVER_NAME'] if not.
You may want to check out the PHP documentation
for more information on these variables.
You may explicitly specify it by setting the hostInfo property.
Warning: Dependent on the server configuration this information may not be reliable and may be faked by the user sending the HTTP request. If the webserver is configured to serve the same site independent of the value of the
Hostheader, this value is not reliable. In such situations you should either fix your webserver configuration or explicitly set the value by setting the hostInfo property. If you don’t have access to the server configuration, you can setupHostControlfilter at application level in order to protect against such kind of attack.
Returns
string|null: Schema and hostname part (with port number if needed) of the request URL (e.g. https://www.yiiframework.com), null if can’t be obtained from $_SERVER and wasn’t set.
See also
getHostName()
Section titled “getHostName() ”public function getHostName(): string|nullReturns the host part of the current request URL.
Value is calculated from current hostInfo property.
Warning: The content of this value may not be reliable, dependent on the server configuration. Please refer to
getHostInfo()for more information.
Returns
string|null: Hostname part of the request URL (e.g. www.yiiframework.com)
Since
2.0.10
See also
getIsAjax()
Section titled “getIsAjax() ”public function getIsAjax(): boolReturns whether this is an AJAX (XMLHttpRequest) request.
Note that in case of cross domain requests, browser doesn’t set the X-Requested-With header by default: https://stackoverflow.com/questions/8163703/cross-domain-ajax-doesnt-send-x-requested-with-header
In case you are using fetch(), pass header manually:
fetch(url, { method: 'GET', headers: {'X-Requested-With': 'XMLHttpRequest'}})Returns
bool: Whether this is an AJAX (XMLHttpRequest) request.
getIsDelete()
Section titled “getIsDelete() ”public function getIsDelete(): boolReturns whether this is a DELETE request.
Returns
bool: Whether this is a DELETE request.
getIsFlash()
Section titled “getIsFlash() ”public function getIsFlash(): boolReturns whether this is an Adobe Flash or Flex request.
Returns
bool: Whether this is an Adobe Flash or Adobe Flex request.
getIsGet()
Section titled “getIsGet() ”public function getIsGet(): boolReturns whether this is a GET request.
Returns
bool: Whether this is a GET request.
getIsHead()
Section titled “getIsHead() ”public function getIsHead(): boolReturns whether this is a HEAD request.
Returns
bool: Whether this is a HEAD request.
getIsOptions()
Section titled “getIsOptions() ”public function getIsOptions(): boolReturns whether this is an OPTIONS request.
Returns
bool: Whether this is a OPTIONS request.
getIsPatch()
Section titled “getIsPatch() ”public function getIsPatch(): boolReturns whether this is a PATCH request.
Returns
bool: Whether this is a PATCH request.
getIsPjax()
Section titled “getIsPjax() ”public function getIsPjax(): boolReturns whether this is a PJAX request.
Returns
bool: Whether this is a PJAX request
getIsPost()
Section titled “getIsPost() ”public function getIsPost(): boolReturns whether this is a POST request.
Returns
bool: Whether this is a POST request.
getIsPut()
Section titled “getIsPut() ”public function getIsPut(): boolReturns whether this is a PUT request.
Returns
bool: Whether this is a PUT request.
getIsSecureConnection()
Section titled “getIsSecureConnection() ”public function getIsSecureConnection(): boolReturn if the request is sent via secure channel (https).
Returns
bool: If the request is sent via secure channel (https)
getMethod()
Section titled “getMethod() ”public function getMethod(): stringReturns the method of the current request (e.g. GET, POST, HEAD, PUT, PATCH, DELETE).
Returns
string: Request method, such as GET, POST, HEAD, PUT, PATCH, DELETE. The value returned is turned into upper case.
getOrigin()
Section titled “getOrigin() ”public function getOrigin(): string|nullReturns the URL origin of a CORS request.
The return value is taken from the Origin header sent by the browser.
Note that the origin request header indicates where a fetch originates from. It doesn’t include any path information, but only the server name. It is sent with a CORS requests, as well as with POST requests. It is similar to the referer header, but, unlike this header, it doesn’t disclose the whole path. Please refer to https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Origin for more information.
Returns
string|null: URL origin of a CORS request, null if not available.
Since
2.0.13
See also
getPathInfo()
Section titled “getPathInfo() ”public function getPathInfo(): stringReturns the path info of the currently requested URL.
A path info refers to the part that is after the entry script and before the question mark (query string). The starting and ending slashes are both removed.
Returns
string: Part of the request URL that is after the entry script and before the question mark. Note, the returned path info is already URL-decoded.
Throws
yii\base\InvalidConfigException: if the path info cannot be determined due to unexpected server configuration
getPort()
Section titled “getPort() ”public function getPort(): intReturns the port to use for insecure requests.
Defaults to 80, or the port specified by the server if the current request is insecure.
getPreferredLanguage()
Section titled “getPreferredLanguage() ”public function getPreferredLanguage(array $languages = []): stringReturns the user-preferred language that should be used by this application.
The language resolution is based on the user preferred languages and the languages supported by the application. The method will try to find the best match.
Parameters
| Parameter | Type | Description |
|---|---|---|
$languages | array | A list of the languages supported by the application. If this is empty, the current application language will be returned without further processing. |
Returns
string: The language that the application should use.
getQueryParam()
Section titled “getQueryParam() ”public function getQueryParam(string $name, mixed $defaultValue = null): mixedReturns the named GET parameter value.
If the GET parameter does not exist, the second parameter passed to this method will be returned.
Parameters
| Parameter | Type | Description |
|---|---|---|
$name | string | The GET parameter name. |
$defaultValue | mixed | The default parameter value if the GET parameter does not exist. |
Returns
mixed: The GET parameter value
See also
getQueryParams()
Section titled “getQueryParams() ”public function getQueryParams(): arrayReturns the request parameters given in the $queryString.
This method will return the contents of $_GET if params where not explicitly set.
getQueryString()
Section titled “getQueryString() ”public function getQueryString(): stringReturns part of the request URL that is after the question mark.
Returns
string: Part of the request URL that is after the question mark
getRawBody()
Section titled “getRawBody() ”public function getRawBody(): stringReturns the raw HTTP request body.
Returns
string: The request body
getReferrer()
Section titled “getReferrer() ”public function getReferrer(): string|nullReturns the URL referrer.
Returns
string|null: URL referrer, null if not available
getRemoteHost()
Section titled “getRemoteHost() ”public function getRemoteHost(): string|nullReturns the host name of the other end of this connection.
This is always the next hop, any headers are ignored.
Returns
string|null: Remote host name, null if not available
Since
2.0.13
See also
getRemoteIP()
Section titled “getRemoteIP() ”public function getRemoteIP(): string|nullReturns the IP on the other end of this connection.
This is always the next hop, any headers are ignored.
Returns
string|null: Remote IP address, null if not available.
Since
2.0.13
getScriptFile()
Section titled “getScriptFile() ”public function getScriptFile(): stringReturns the entry script file path.
The default implementation will simply return $_SERVER['SCRIPT_FILENAME'].
getScriptUrl()
Section titled “getScriptUrl() ”public function getScriptUrl(): stringReturns the relative URL of the entry script.
The implementation of this method referenced Zend_Controller_Request_Http in Zend Framework.
Returns
string: The relative URL of the entry script.
Throws
yii\base\InvalidConfigException: if unable to determine the entry script URL
getSecurePort()
Section titled “getSecurePort() ”public function getSecurePort(): intReturns the port to use for secure requests.
Defaults to 443, or the port specified by the server if the current request is secure.
getServerName()
Section titled “getServerName() ”public function getServerName(): string|nullReturns the server name.
Returns
string|null: Server name, null if not available
getServerPort()
Section titled “getServerPort() ”public function getServerPort(): int|nullReturns the server port number. If a port is specified via a forwarding header (e.g. ‘X-Forwarded-Port’)
and the remote host is a “trusted host” the that port will be used (see $portHeaders),
otherwise the default server port will be returned.
getUrl()
Section titled “getUrl() ”public function getUrl(): stringReturns the currently requested relative URL.
This refers to the portion of the URL that is after the $hostInfo part.
It includes the $queryString part if any.
Returns
string: The currently requested relative URL. Note that the URI returned may be URL-encoded depending on the client.
Throws
yii\base\InvalidConfigException: if the URL cannot be determined due to unusual server configuration
getUserAgent()
Section titled “getUserAgent() ”public function getUserAgent(): string|nullReturns the user agent.
Returns
string|null: User agent, null if not available
getUserHost()
Section titled “getUserHost() ”public function getUserHost(): string|nullReturns the user host name.
The HOST is determined using headers and / or $_SERVER variables.
Returns
string|null: User host name, null if not available
getUserIP()
Section titled “getUserIP() ”public function getUserIP(): string|nullReturns the user IP address.
The IP is determined using headers and / or $_SERVER variables.
Returns
string|null: User IP address, null if not available
parseAcceptHeader()
Section titled “parseAcceptHeader() ”public function parseAcceptHeader(string $header): arrayParses the given Accept (or Accept-Language) header.
This method will return the acceptable values with their quality scores and the corresponding parameters
as specified in the given Accept header. The array keys of the return value are the acceptable values,
while the array values consisting of the corresponding quality scores and parameters. The acceptable
values with the highest quality scores will be returned first. For example,
$header = 'text/plain; q=0.5, application/json; version=1.0, application/xml; version=2.0;';$accepts = $request->parseAcceptHeader($header);print_r($accepts);// displays:// [// 'application/json' => ['q' => 1, 'version' => '1.0'],// 'application/xml' => ['q' => 1, 'version' => '2.0'],// 'text/plain' => ['q' => 0.5],// ]Parameters
| Parameter | Type | Description |
|---|---|---|
$header | string | The header to be parsed |
Returns
array: The acceptable values ordered by their quality score. The values with the highest scores will be returned first.
post()
Section titled “post() ”public function post(string|null $name = null, mixed $defaultValue = null): mixedReturns POST parameter with a given name. If name isn’t specified, returns an array of all POST parameters.
Parameters
| Parameter | Type | Description |
|---|---|---|
$name | string| | The parameter name |
$defaultValue | mixed | The default parameter value if the parameter does not exist. |
Returns
mixed
resolve()
Section titled “resolve() ”public function resolve(): arrayResolves the current request into a route and the associated parameters.
Returns
array: The first element is the route, and the second is the associated parameters.
Throws
NotFoundHttpException: if the request cannot be resolved.
setAcceptableContentTypes()
Section titled “setAcceptableContentTypes() ”public function setAcceptableContentTypes(array $value): mixedSets the acceptable content types.
Please refer to getAcceptableContentTypes() on the format of the parameter.
Parameters
| Parameter | Type | Description |
|---|---|---|
$value | array | The content types that are acceptable by the end user. They should be ordered by the preference level. |
Returns
mixed
See also
setAcceptableLanguages()
Section titled “setAcceptableLanguages() ”public function setAcceptableLanguages(array $value): mixedParameters
| Parameter | Type | Description |
|---|---|---|
$value | array | The languages that are acceptable by the end user. They should be ordered by the preference level. |
Returns
mixed
setBaseUrl()
Section titled “setBaseUrl() ”public function setBaseUrl(string $value): mixedSets the relative URL for the application.
By default the URL is determined based on the entry script URL. This setter is provided in case you want to change this behavior.
Parameters
| Parameter | Type | Description |
|---|---|---|
$value | string | The relative URL for the application |
Returns
mixed
setBodyParams()
Section titled “setBodyParams() ”public function setBodyParams(mixed $values): mixedSets the request body parameters.
Parameters
| Parameter | Type | Description |
|---|---|---|
$values | mixed | The request body parameters (name-value pairs) |
Returns
mixed
See also
setHostInfo()
Section titled “setHostInfo() ”public function setHostInfo(string|null $value): mixedSets the schema and host part of the application URL.
This setter is provided in case the schema and hostname cannot be determined on certain Web servers.
Parameters
| Parameter | Type | Description |
|---|---|---|
$value | string| | The schema and host part of the application URL. The trailing slashes will be removed. |
Returns
mixed
See also
getHostInfo()(for security related notes on this property.)
setPathInfo()
Section titled “setPathInfo() ”public function setPathInfo(string $value): mixedSets the path info of the current request.
This method is mainly provided for testing purpose.
Parameters
| Parameter | Type | Description |
|---|---|---|
$value | string | The path info of the current request |
Returns
mixed
setPort()
Section titled “setPort() ”public function setPort(int $value): mixedSets the port to use for insecure requests.
This setter is provided in case a custom port is necessary for certain server configurations.
Parameters
| Parameter | Type | Description |
|---|---|---|
$value | int | Port number. |
Returns
mixed
setQueryParams()
Section titled “setQueryParams() ”public function setQueryParams(array $values): mixedSets the request $queryString parameters.
Parameters
| Parameter | Type | Description |
|---|---|---|
$values | array | The request query parameters (name-value pairs) |
Returns
mixed
See also
setRawBody()
Section titled “setRawBody() ”public function setRawBody(string $rawBody): mixedSets the raw HTTP request body, this method is mainly used by test scripts to simulate raw HTTP requests.
Parameters
| Parameter | Type | Description |
|---|---|---|
$rawBody | string | The request body |
Returns
mixed
setScriptFile()
Section titled “setScriptFile() ”public function setScriptFile(string $value): mixedSets the entry script file path.
The entry script file path normally can be obtained from $_SERVER['SCRIPT_FILENAME'].
If your server configuration does not return the correct value, you may configure
this property to make it right.
Parameters
| Parameter | Type | Description |
|---|---|---|
$value | string | The entry script file path. |
Returns
mixed
setScriptUrl()
Section titled “setScriptUrl() ”public function setScriptUrl(string $value): mixedSets the relative URL for the application entry script.
This setter is provided in case the entry script URL cannot be determined on certain Web servers.
Parameters
| Parameter | Type | Description |
|---|---|---|
$value | string | The relative URL for the application entry script. |
Returns
mixed
setSecurePort()
Section titled “setSecurePort() ”public function setSecurePort(int $value): mixedSets the port to use for secure requests.
This setter is provided in case a custom port is necessary for certain server configurations.
Parameters
| Parameter | Type | Description |
|---|---|---|
$value | int | Port number. |
Returns
mixed
setUrl()
Section titled “setUrl() ”public function setUrl(string $value): mixedSets the currently requested relative URL.
The URI must refer to the portion that is after $hostInfo.
Note that the URI should be URL-encoded.
Parameters
| Parameter | Type | Description |
|---|---|---|
$value | string | The request URI to be set |
Returns
mixed
validateCsrfToken()
Section titled “validateCsrfToken() ”public function validateCsrfToken(string|null $clientSuppliedToken = null): boolPerforms the CSRF validation.
This method will validate the user-provided CSRF token by comparing it with the one stored in cookie or session.
This method is mainly called in Controller::beforeAction().
Note that the method will NOT perform CSRF validation if $enableCsrfValidation is false or the HTTP method
is among GET, HEAD or OPTIONS.
Parameters
| Parameter | Type | Description |
|---|---|---|
$clientSuppliedToken | string| | The user-provided CSRF token to be validated. If null, the token will be retrieved from the $csrfParam POST field or HTTP header. This parameter is available since version 2.0.4. |
Returns
bool: Whether CSRF token is valid. If $enableCsrfValidation is false, this method will return true.
createCsrfCookie()
Section titled “createCsrfCookie() ”protected function createCsrfCookie(string $token): yii\web\CookieCreates a cookie with a randomly generated CSRF token.
Initial values specified in $csrfCookie will be applied to the generated cookie.
Parameters
| Parameter | Type | Description |
|---|---|---|
$token | string | The CSRF token |
Returns
Cookie: The generated cookie
See also
filterHeaders()
Section titled “filterHeaders() ”protected function filterHeaders(yii\web\HeaderCollection $headerCollection): mixedFilters headers according to the $trustedHosts.
generateCsrfToken()
Section titled “generateCsrfToken() ”protected function generateCsrfToken(): stringGenerates an unmasked random token used to perform CSRF validation.
Returns
string: The random token for CSRF validation.
getIpValidator()
Section titled “getIpValidator() ”protected function getIpValidator(): yii\validators\IpValidatorCreates instance of IpValidator.
You can override this method to adjust validator or implement different matching strategy.
getSecureForwardedHeaderParts()
Section titled “getSecureForwardedHeaderParts() ”protected function getSecureForwardedHeaderParts(): arrayReturns decoded forwarded header
Returns
array
Since
2.0.31
getSecureForwardedHeaderTrustedPart()
Section titled “getSecureForwardedHeaderTrustedPart() ”protected function getSecureForwardedHeaderTrustedPart(string $token): string|nullGets first Forwarded header value for token
Parameters
| Parameter | Type | Description |
|---|---|---|
$token | string | Header token |
Returns
string|null
Since
2.0.31
getSecureForwardedHeaderTrustedParts()
Section titled “getSecureForwardedHeaderTrustedParts() ”protected function getSecureForwardedHeaderTrustedParts(): arrayGets only trusted Forwarded header parts
Returns
array
Since
2.0.31
getTrustedHeaders()
Section titled “getTrustedHeaders() ”protected function getTrustedHeaders(): arrayTrusted headers according to the $trustedHosts.
Returns
array
Since
2.0.28
getUserIpFromIpHeader()
Section titled “getUserIpFromIpHeader() ”protected function getUserIpFromIpHeader(string $ips): string|nullReturn user IP’s from IP header.
Parameters
| Parameter | Type | Description |
|---|---|---|
$ips | string | Comma separated IP list |
Returns
string|null: IP as string. Null is returned if IP can not be determined from header.
Since
2.0.28
See also
getUserIpFromIpHeaders()
Section titled “getUserIpFromIpHeaders() ”protected function getUserIpFromIpHeaders(): string|nullReturns the user IP address from $ipHeaders.
loadCookies()
Section titled “loadCookies() ”protected function loadCookies(): arrayConverts $_COOKIE into an array of Cookie.
Returns
array: The cookies obtained from request
Throws
yii\base\InvalidConfigException: if$cookieValidationKeyis not set when$enableCookieValidationis true
loadCsrfToken()
Section titled “loadCsrfToken() ”protected function loadCsrfToken(): string|nullLoads the CSRF token from cookie or session.
Returns
string|null: The CSRF token loaded from cookie or session. Null is returned if the cookie or session does not have CSRF token.
resolvePathInfo()
Section titled “resolvePathInfo() ”protected function resolvePathInfo(): stringResolves the path info part of the currently requested URL.
A path info refers to the part that is after the entry script and before the question mark (query string). The starting slashes are both removed (ending slashes will be kept).
Returns
string: Part of the request URL that is after the entry script and before the question mark. Note, the returned path info is decoded.
Throws
yii\base\InvalidConfigException: if the path info cannot be determined due to unexpected server configuration
resolveRequestUri()
Section titled “resolveRequestUri() ”protected function resolveRequestUri(): string|boolResolves the request URI portion for the currently requested URL.
This refers to the portion that is after the $hostInfo part. It includes the $queryString part if any.
The implementation of this method referenced Zend_Controller_Request_Http in Zend Framework.
Returns
string|bool: The request URI portion for the currently requested URL. Note that the URI returned may be URL-encoded depending on the client.
Throws
yii\base\InvalidConfigException: if the request URI cannot be determined due to unusual server configuration