Class yii\web\Request

Inheritanceyii\web\Request » yii\base\Request » yii\base\Component » yii\base\BaseObject
Implementsyii\base\Configurable
Available since version2.0
Source Code https://github.com/yiisoft/yii2/blob/master/framework/web/Request.php

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 yii\web\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.

Public Properties

Hide inherited properties

PropertyTypeDescriptionDefined By
$absoluteUrl string The currently requested absolute URL. This property is read-only. yii\web\Request
$acceptableContentTypes 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. yii\web\Request
$acceptableLanguages array The languages ordered by the preference level. The first element represents the most preferred language. yii\web\Request
$authCredentials 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. This property is read-only. yii\web\Request
$authPassword string|null The password sent via HTTP authentication, null if the password is not given. This property is read-only. yii\web\Request
$authUser string|null The username sent via HTTP authentication, null if the username is not given. This property is read-only. yii\web\Request
$baseUrl string The relative URL for the application (usually with a leading slash). yii\web\Request
$behaviors yii\base\Behavior[] List of behaviors attached to this component. This property is read-only. yii\base\Component
$bodyParams array The request parameters given in the request body. yii\web\Request
$contentType string Request content-type. Null is returned if this information is not available. This property is read-only. yii\web\Request
$cookieValidationKey string A secret key used for cookie validation. yii\web\Request
$cookies yii\web\CookieCollection The cookie collection. This property is read-only. yii\web\Request
$csrfCookie array The configuration for creating the CSRF cookie. yii\web\Request
$csrfParam string The name of the token used to prevent CSRF. yii\web\Request
$csrfToken string The token used to perform CSRF validation. This property is read-only. yii\web\Request
$csrfTokenFromHeader string The CSRF token sent via CSRF_HEADER by browser. Null is returned if no such header is sent. This property is read-only. yii\web\Request
$eTags array The entity tags. This property is read-only. yii\web\Request
$enableCookieValidation boolean Whether cookies should be validated to ensure they are not tampered. yii\web\Request
$enableCsrfCookie boolean Whether to use cookie to persist CSRF token. yii\web\Request
$enableCsrfValidation boolean Whether to enable CSRF (Cross-Site Request Forgery) validation. yii\web\Request
$headers yii\web\HeaderCollection The header collection. This property is read-only. yii\web\Request
$hostInfo string|null Schema and hostname part (with port number if needed) of the request URL (e.g. http://www.yiiframework.com), null if can't be obtained from $_SERVER and wasn't set. See getHostInfo() for security related notes on this property. yii\web\Request
$hostName string|null Hostname part of the request URL (e.g. www.yiiframework.com). This property is read-only. yii\web\Request
$ipHeaders string[] List of headers where proxies store the real client IP. yii\web\Request
$isAjax boolean Whether this is an AJAX (XMLHttpRequest) request. This property is read-only. yii\web\Request
$isConsoleRequest boolean The value indicating whether the current request is made via console yii\base\Request
$isDelete boolean Whether this is a DELETE request. This property is read-only. yii\web\Request
$isFlash boolean Whether this is an Adobe Flash or Adobe Flex request. This property is read-only. yii\web\Request
$isGet boolean Whether this is a GET request. This property is read-only. yii\web\Request
$isHead boolean Whether this is a HEAD request. This property is read-only. yii\web\Request
$isOptions boolean Whether this is a OPTIONS request. This property is read-only. yii\web\Request
$isPatch boolean Whether this is a PATCH request. This property is read-only. yii\web\Request
$isPjax boolean Whether this is a PJAX request. This property is read-only. yii\web\Request
$isPost boolean Whether this is a POST request. This property is read-only. yii\web\Request
$isPut boolean Whether this is a PUT request. This property is read-only. yii\web\Request
$isSecureConnection boolean If the request is sent via secure channel (https). This property is read-only. yii\web\Request
$method string Request method, such as GET, POST, HEAD, PUT, PATCH, DELETE. The value returned is turned into upper case. This property is read-only. yii\web\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. yii\web\Request
$origin string|null URL origin of a CORS request, null if not available. This property is read-only. yii\web\Request
$parsers array The parsers for converting the raw HTTP request body into $bodyParams. yii\web\Request
$pathInfo 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. yii\web\Request
$port integer Port number for insecure requests. yii\web\Request
$preferredLanguage string The language that the application should use. yii\web\Request
$queryParams array The request GET parameter values. yii\web\Request
$queryString string Part of the request URL that is after the question mark. This property is read-only. yii\web\Request
$rawBody string The request body. yii\web\Request
$referrer string|null URL referrer, null if not available. This property is read-only. yii\web\Request
$remoteHost string|null Remote host name, null if not available. This property is read-only. yii\web\Request
$remoteIP string|null Remote IP address, null if not available. This property is read-only. yii\web\Request
$scriptFile string The entry script file path. yii\web\Request
$scriptUrl string The relative URL of the entry script. yii\web\Request
$secureHeaders array Lists of headers that are, by default, subject to the trusted host configuration. yii\web\Request
$securePort integer Port number for secure requests. yii\web\Request
$secureProtocolHeaders array List of headers to check for determining whether the connection is made via HTTPS. yii\web\Request
$serverName string Server name, null if not available. This property is read-only. yii\web\Request
$serverPort integer|null Server port number, null if not available. This property is read-only. yii\web\Request
$trustedHosts array The configuration for trusted security related headers. yii\web\Request
$url string The currently requested relative URL. Note that the URI returned may be URL-encoded depending on the client. yii\web\Request
$userAgent string|null User agent, null if not available. This property is read-only. yii\web\Request
$userHost string|null User host name, null if not available. This property is read-only. yii\web\Request
$userIP string|null User IP address, null if not available. This property is read-only. yii\web\Request

Public Methods

Hide inherited methods

MethodDescriptionDefined By
__call() Calls the named method which is not a class method. yii\base\BaseObject
__clone() This method is called after the object is created by cloning an existing one. yii\base\Component
__construct() Constructor. yii\base\BaseObject
__get() Returns the value of an object property. yii\base\BaseObject
__isset() Checks if a property is set, i.e. defined and not null. yii\base\BaseObject
__set() Sets value of an object property. yii\base\BaseObject
__unset() Sets an object property to null. yii\base\BaseObject
attachBehavior() Attaches a behavior to this component. yii\base\Component
attachBehaviors() Attaches a list of behaviors to the component. yii\base\Component
behaviors() Returns a list of behaviors that this component should behave as. yii\base\Component
canGetProperty() Returns a value indicating whether a property can be read. yii\base\BaseObject
canSetProperty() Returns a value indicating whether a property can be set. yii\base\BaseObject
className() Returns the fully qualified name of this class. yii\base\BaseObject
detachBehavior() Detaches a behavior from the component. yii\base\Component
detachBehaviors() Detaches all behaviors from the component. yii\base\Component
ensureBehaviors() Makes sure that the behaviors declared in behaviors() are attached to this component. yii\base\Component
get() Returns GET parameter with a given name. If name isn't specified, returns an array of all GET parameters. yii\web\Request
getAbsoluteUrl() Returns the currently requested absolute URL. yii\web\Request
getAcceptableContentTypes() Returns the content types acceptable by the end user. yii\web\Request
getAcceptableLanguages() Returns the languages acceptable by the end user. yii\web\Request
getAuthCredentials() yii\web\Request
getAuthPassword() yii\web\Request
getAuthUser() yii\web\Request
getBaseUrl() Returns the relative URL for the application. yii\web\Request
getBehavior() Returns the named behavior object. yii\base\Component
getBehaviors() Returns all behaviors attached to this component. yii\base\Component
getBodyParam() Returns the named request body parameter value. yii\web\Request
getBodyParams() Returns the request parameters given in the request body. yii\web\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. yii\web\Request
getCookies() Returns the cookie collection. yii\web\Request
getCsrfToken() Returns the token used to perform CSRF validation. yii\web\Request
getCsrfTokenFromHeader() yii\web\Request
getETags() Gets the Etags. yii\web\Request
getHeaders() Returns the header collection. yii\web\Request
getHostInfo() Returns the schema and host part of the current request URL. yii\web\Request
getHostName() Returns the host part of the current request URL. yii\web\Request
getIsAjax() Returns whether this is an AJAX (XMLHttpRequest) request. yii\web\Request
getIsConsoleRequest() Returns a value indicating whether the current request is made via command line. yii\base\Request
getIsDelete() Returns whether this is a DELETE request. yii\web\Request
getIsFlash() Returns whether this is an Adobe Flash or Flex request. yii\web\Request
getIsGet() Returns whether this is a GET request. yii\web\Request
getIsHead() Returns whether this is a HEAD request. yii\web\Request
getIsOptions() Returns whether this is an OPTIONS request. yii\web\Request
getIsPatch() Returns whether this is a PATCH request. yii\web\Request
getIsPjax() Returns whether this is a PJAX request. yii\web\Request
getIsPost() Returns whether this is a POST request. yii\web\Request
getIsPut() Returns whether this is a PUT request. yii\web\Request
getIsSecureConnection() Return if the request is sent via secure channel (https). yii\web\Request
getMethod() Returns the method of the current request (e.g. GET, POST, HEAD, PUT, PATCH, DELETE). yii\web\Request
getOrigin() Returns the URL origin of a CORS request. yii\web\Request
getPathInfo() Returns the path info of the currently requested URL. yii\web\Request
getPort() Returns the port to use for insecure requests. yii\web\Request
getPreferredLanguage() Returns the user-preferred language that should be used by this application. yii\web\Request
getQueryParam() Returns the named GET parameter value. yii\web\Request
getQueryParams() Returns the request parameters given in the $queryString. yii\web\Request
getQueryString() Returns part of the request URL that is after the question mark. yii\web\Request
getRawBody() Returns the raw HTTP request body. yii\web\Request
getReferrer() Returns the URL referrer. yii\web\Request
getRemoteHost() Returns the host name of the other end of this connection. yii\web\Request
getRemoteIP() Returns the IP on the other end of this connection. yii\web\Request
getScriptFile() Returns the entry script file path. yii\web\Request
getScriptUrl() Returns the relative URL of the entry script. yii\web\Request
getSecurePort() Returns the port to use for secure requests. yii\web\Request
getServerName() Returns the server name. yii\web\Request
getServerPort() Returns the server port number. yii\web\Request
getUrl() Returns the currently requested relative URL. yii\web\Request
getUserAgent() Returns the user agent. yii\web\Request
getUserHost() Returns the user host name. yii\web\Request
getUserIP() Returns the user IP address. yii\web\Request
hasEventHandlers() Returns a value indicating whether there is any handler attached to the named event. yii\base\Component
hasMethod() Returns a value indicating whether a method is defined. yii\base\BaseObject
hasProperty() Returns a value indicating whether a property is defined. yii\base\BaseObject
init() Initializes the object. yii\base\BaseObject
off() Detaches an existing event handler from this component. yii\base\Component
on() Attaches an event handler to an event. yii\base\Component
parseAcceptHeader() Parses the given Accept (or Accept-Language) header. yii\web\Request
post() Returns POST parameter with a given name. If name isn't specified, returns an array of all POST parameters. yii\web\Request
resolve() Resolves the current request into a route and the associated parameters. yii\web\Request
setAcceptableContentTypes() Sets the acceptable content types. yii\web\Request
setAcceptableLanguages() yii\web\Request
setBaseUrl() Sets the relative URL for the application. yii\web\Request
setBodyParams() Sets the request body parameters. yii\web\Request
setHostInfo() Sets the schema and host part of the application URL. yii\web\Request
setIsConsoleRequest() Sets the value indicating whether the current request is made via command line. yii\base\Request
setPathInfo() Sets the path info of the current request. yii\web\Request
setPort() Sets the port to use for insecure requests. yii\web\Request
setQueryParams() Sets the request $queryString parameters. yii\web\Request
setRawBody() Sets the raw HTTP request body, this method is mainly used by test scripts to simulate raw HTTP requests. yii\web\Request
setScriptFile() Sets the entry script file path. yii\web\Request
setScriptUrl() Sets the relative URL for the application entry script. yii\web\Request
setSecurePort() Sets the port to use for secure requests. yii\web\Request
setUrl() Sets the currently requested relative URL. yii\web\Request
trigger() Triggers an event. yii\base\Component
validateCsrfToken() Performs the CSRF validation. yii\web\Request

Protected Methods

Hide inherited methods

MethodDescriptionDefined By
createCsrfCookie() Creates a cookie with a randomly generated CSRF token. yii\web\Request
filterHeaders() Filters headers according to the $trustedHosts. yii\web\Request
generateCsrfToken() Generates an unmasked random token used to perform CSRF validation. yii\web\Request
getIpValidator() Creates instance of yii\validators\IpValidator. yii\web\Request
getSecureForwardedHeaderParts() Returns decoded forwarded header yii\web\Request
getSecureForwardedHeaderTrustedPart() Gets first Forwarded header value for token yii\web\Request
getSecureForwardedHeaderTrustedParts() Gets only trusted Forwarded header parts yii\web\Request
getTrustedHeaders() Trusted headers according to the $trustedHosts. yii\web\Request
getUserIpFromIpHeader() Return user IP's from IP header. yii\web\Request
getUserIpFromIpHeaders() Returns the user IP address from $ipHeaders. yii\web\Request
loadCookies() Converts $_COOKIE into an array of yii\web\Cookie. yii\web\Request
loadCsrfToken() Loads the CSRF token from cookie or session. yii\web\Request
resolvePathInfo() Resolves the path info part of the currently requested URL. yii\web\Request
resolveRequestUri() Resolves the request URI portion for the currently requested URL. yii\web\Request

Constants

Hide inherited constants

ConstantValueDescriptionDefined By
CSRF_HEADER 'X-CSRF-Token' The name of the HTTP header for sending CSRF token. yii\web\Request
CSRF_MASK_LENGTH 8 The length of the CSRF token mask. Deprecated since 2.0.12. The mask length is now equal to the token length. yii\web\Request

Property Details

$absoluteUrl public property

The currently requested absolute URL. This property is read-only.

public string $absoluteUrl null
$acceptableContentTypes public property

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.

$acceptableLanguages public property

The languages ordered by the preference level. The first element represents the most preferred language.

$authCredentials public property

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. This property is read-only.

public array $authCredentials null
$authPassword public property

The password sent via HTTP authentication, null if the password is not given. This property is read-only.

public string|null $authPassword null
$authUser public property

The username sent via HTTP authentication, null if the username is not given. This property is read-only.

public string|null $authUser null
$baseUrl public property

The relative URL for the application (usually with a leading slash).

public string $baseUrl null
$bodyParams public property

The request parameters given in the request body.

public array $bodyParams null
$contentType public property

Request content-type. Null is returned if this information is not available. This property is read-only.

public string $contentType null
$cookieValidationKey public property

A secret key used for cookie validation. This property must be set if $enableCookieValidation is true.

$cookies public property

The cookie collection. This property is read-only.

$csrfCookie public property

The configuration for creating the CSRF cookie. This property is used only when both $enableCsrfValidation and $enableCsrfCookie are true.

public array $csrfCookie = ['httpOnly' => true]
$csrfParam public property

The name of the token used to prevent CSRF. Defaults to '_csrf'. This property is used only when $enableCsrfValidation is true.

public string $csrfParam '_csrf'
$csrfToken public property

The token used to perform CSRF validation. This property is read-only.

public string $csrfToken null
$csrfTokenFromHeader public property

The CSRF token sent via CSRF_HEADER by browser. Null is returned if no such header is sent. This property is read-only.

$eTags public property

The entity tags. This property is read-only.

public array $eTags null
$enableCookieValidation public property

Whether cookies should be validated to ensure they are not tampered. Defaults to true.

$enableCsrfCookie public property

Whether 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.

public boolean $enableCsrfCookie true
$enableCsrfValidation public property

Whether 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 yii\helpers\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 yii\web\YiiAsset asset must be registered. You also need to include CSRF meta tags in your pages by using yii\helpers\Html::csrfMetaTags().

See also:

$headers public property

The header collection. This property is read-only.

$hostInfo public property

Schema and hostname part (with port number if needed) of the request URL (e.g. http://www.yiiframework.com), null if can't be obtained from $_SERVER and wasn't set. See getHostInfo() for security related notes on this property.

public string|null $hostInfo null
$hostName public property

Hostname part of the request URL (e.g. www.yiiframework.com). This property is read-only.

public string|null $hostName null
$ipHeaders public property (available since version 2.0.13)

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.

See also:

public string[] $ipHeaders = ['X-Forwarded-For']
$isAjax public property

Whether this is an AJAX (XMLHttpRequest) request. This property is read-only.

public boolean $isAjax null
$isDelete public property

Whether this is a DELETE request. This property is read-only.

public boolean $isDelete null
$isFlash public property

Whether this is an Adobe Flash or Adobe Flex request. This property is read-only.

public boolean $isFlash null
$isGet public property

Whether this is a GET request. This property is read-only.

public boolean $isGet null
$isHead public property

Whether this is a HEAD request. This property is read-only.

public boolean $isHead null
$isOptions public property

Whether this is a OPTIONS request. This property is read-only.

public boolean $isOptions null
$isPatch public property

Whether this is a PATCH request. This property is read-only.

public boolean $isPatch null
$isPjax public property

Whether this is a PJAX request. This property is read-only.

public boolean $isPjax null
$isPost public property

Whether this is a POST request. This property is read-only.

public boolean $isPost null
$isPut public property

Whether this is a PUT request. This property is read-only.

public boolean $isPut null
$isSecureConnection public property

If the request is sent via secure channel (https). This property is read-only.

$method public property

Request method, such as GET, POST, HEAD, PUT, PATCH, DELETE. The value returned is turned into upper case. This property is read-only.

public string $method null
$methodParam public property

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'.

See also:

public string $methodParam '_method'
$origin public property

URL origin of a CORS request, null if not available. This property is read-only.

public string|null $origin null
$parsers public property

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 yii\web\RequestParserInterface.

To enable parsing for JSON requests you can use the yii\web\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.

See also getBodyParams().

public array $parsers = []
$pathInfo public property

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.

public string $pathInfo null
$port public property

Port number for insecure requests.

public integer $port null
$preferredLanguage public read-only property

The language that the application should use.

public string getPreferredLanguage ( array $languages = [] )
$queryParams public property

The request GET parameter values.

public array $queryParams null
$queryString public property

Part of the request URL that is after the question mark. This property is read-only.

public string $queryString null
$rawBody public property

The request body.

public string $rawBody null
$referrer public property

URL referrer, null if not available. This property is read-only.

public string|null $referrer null
$remoteHost public property

Remote host name, null if not available. This property is read-only.

public string|null $remoteHost null
$remoteIP public property

Remote IP address, null if not available. This property is read-only.

public string|null $remoteIP null
$scriptFile public property

The entry script file path.

public string $scriptFile null
$scriptUrl public property

The relative URL of the entry script.

public string $scriptUrl null
$secureHeaders public property (available since version 2.0.13)

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.

See also:

public array $secureHeaders = ['X-Forwarded-For''X-Forwarded-Host''X-Forwarded-Proto''Front-End-Https''X-Rewrite-Url''X-Original-Host']
$securePort public property

Port number for secure requests.

public integer $securePort null
$secureProtocolHeaders public property (available since version 2.0.13)

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.

See also:

public array $secureProtocolHeaders = ['X-Forwarded-Proto' => ['https'], 'Front-End-Https' => ['on']]
$serverName public property

Server name, null if not available. This property is read-only.

public string $serverName null
$serverPort public property

Server port number, null if not available. This property is read-only.

public integer|null $serverPort null
$trustedHosts public property (available since version 2.0.13)

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 yii\validators\IpValidator. See IpValidator::::setRanges() and yii\validators\IpValidator::$networks for advanced matching.

See also $secureHeaders.

public array $trustedHosts = []
$url public property

The currently requested relative URL. Note that the URI returned may be URL-encoded depending on the client.

public string $url null
$userAgent public property

User agent, null if not available. This property is read-only.

public string|null $userAgent null
$userHost public property

User host name, null if not available. This property is read-only.

public string|null $userHost null
$userIP public property

User IP address, null if not available. This property is read-only.

public string|null $userIP null

Method Details

createCsrfCookie() protected method

Creates a cookie with a randomly generated CSRF token.

Initial values specified in $csrfCookie will be applied to the generated cookie.

See also $enableCsrfValidation.

protected yii\web\Cookie createCsrfCookie ( $token )
$token string

The CSRF token

return yii\web\Cookie

The generated cookie

filterHeaders() protected method (available since version 2.0.13)

Filters headers according to the $trustedHosts.

protected void filterHeaders ( yii\web\HeaderCollection $headerCollection )
$headerCollection yii\web\HeaderCollection
generateCsrfToken() protected method

Generates an unmasked random token used to perform CSRF validation.

protected string generateCsrfToken ( )
return string

The random token for CSRF validation.

get() public method

Returns GET parameter with a given name. If name isn't specified, returns an array of all GET parameters.

public array|mixed get ( $name null, $defaultValue null )
$name string

The parameter name

$defaultValue mixed

The default parameter value if the parameter does not exist.

getAbsoluteUrl() public method

Returns the currently requested absolute URL.

This is a shortcut to the concatenation of $hostInfo and $url.

public string getAbsoluteUrl ( )
return string

The currently requested absolute URL.

getAcceptableContentTypes() public method

Returns 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],
// ]
public array getAcceptableContentTypes ( )
return 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() public method

Returns the languages acceptable by the end user.

This is determined by the Accept-Language HTTP header.

public array getAcceptableLanguages ( )
return array

The languages ordered by the preference level. The first element represents the most preferred language.

getAuthCredentials() public method (available since version 2.0.13)

See also:

public array getAuthCredentials ( )
return 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
getAuthPassword() public method

See also getAuthCredentials() to get both username and password in one call.

public string|null getAuthPassword ( )
return string|null

The password sent via HTTP authentication, null if the password is not given

getAuthUser() public method

See also getAuthCredentials() to get both username and password in one call.

public string|null getAuthUser ( )
return string|null

The username sent via HTTP authentication, null if the username is not given

getBaseUrl() public method

Returns 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.

See also setScriptUrl().

public string getBaseUrl ( )
return string

The relative URL for the application

getBodyParam() public method

Returns the named request body parameter value.

If the parameter does not exist, the second parameter passed to this method will be returned.

See also:

public mixed getBodyParam ( $name, $defaultValue null )
$name string

The parameter name

$defaultValue mixed

The default parameter value if the parameter does not exist.

return mixed

The parameter value

getBodyParams() public method

Returns 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.

See also:

public array getBodyParams ( )
return array

The request parameters given in the request body.

throws yii\base\InvalidConfigException

if a registered parser does not implement the yii\web\RequestParserInterface.

getContentType() public method

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.

For the MIME-types the user expects in response, see $acceptableContentTypes.

public string getContentType ( )
return string

Request content-type. Null is returned if this information is not available.

getCookies() public method

Returns 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');
public yii\web\CookieCollection getCookies ( )
return yii\web\CookieCollection

The cookie collection.

getCsrfToken() public method

Returns 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.

public string getCsrfToken ( $regenerate false )
$regenerate boolean

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).

return string

The token used to perform CSRF validation.

getCsrfTokenFromHeader() public method

public string getCsrfTokenFromHeader ( )
return string

The CSRF token sent via CSRF_HEADER by browser. Null is returned if no such header is sent.

getETags() public method

Gets the Etags.

public array getETags ( )
return array

The entity tags

getHeaders() public method

Returns the header collection.

The header collection contains incoming HTTP headers.

public yii\web\HeaderCollection getHeaders ( )
return yii\web\HeaderCollection

The header collection

getHostInfo() public method

Returns 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 Host header, 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 setup yii\filters\HostControl filter at application level in order to protect against such kind of attack.

See also setHostInfo().

public string|null getHostInfo ( )
return string|null

Schema and hostname part (with port number if needed) of the request URL (e.g. http://www.yiiframework.com), null if can't be obtained from $_SERVER and wasn't set.

getHostName() public method (available since version 2.0.10)

Returns 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.

See also getHostInfo().

public string|null getHostName ( )
return string|null

Hostname part of the request URL (e.g. www.yiiframework.com)

getIpValidator() protected method (available since version 2.0.13)

Creates instance of yii\validators\IpValidator.

You can override this method to adjust validator or implement different matching strategy.

protected yii\validators\IpValidator getIpValidator ( )
getIsAjax() public method

Returns 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'}
})
public boolean getIsAjax ( )
return boolean

Whether this is an AJAX (XMLHttpRequest) request.

getIsDelete() public method

Returns whether this is a DELETE request.

public boolean getIsDelete ( )
return boolean

Whether this is a DELETE request.

getIsFlash() public method

Returns whether this is an Adobe Flash or Flex request.

public boolean getIsFlash ( )
return boolean

Whether this is an Adobe Flash or Adobe Flex request.

getIsGet() public method

Returns whether this is a GET request.

public boolean getIsGet ( )
return boolean

Whether this is a GET request.

getIsHead() public method

Returns whether this is a HEAD request.

public boolean getIsHead ( )
return boolean

Whether this is a HEAD request.

getIsOptions() public method

Returns whether this is an OPTIONS request.

public boolean getIsOptions ( )
return boolean

Whether this is a OPTIONS request.

getIsPatch() public method

Returns whether this is a PATCH request.

public boolean getIsPatch ( )
return boolean

Whether this is a PATCH request.

getIsPjax() public method

Returns whether this is a PJAX request.

public boolean getIsPjax ( )
return boolean

Whether this is a PJAX request

getIsPost() public method

Returns whether this is a POST request.

public boolean getIsPost ( )
return boolean

Whether this is a POST request.

getIsPut() public method

Returns whether this is a PUT request.

public boolean getIsPut ( )
return boolean

Whether this is a PUT request.

getIsSecureConnection() public method

Return if the request is sent via secure channel (https).

public boolean getIsSecureConnection ( )
return boolean

If the request is sent via secure channel (https)

getMethod() public method

Returns the method of the current request (e.g. GET, POST, HEAD, PUT, PATCH, DELETE).

public string getMethod ( )
return string

Request method, such as GET, POST, HEAD, PUT, PATCH, DELETE. The value returned is turned into upper case.

getOrigin() public method (available since version 2.0.13)

Returns 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.

See also getHeaders().

public string|null getOrigin ( )
return string|null

URL origin of a CORS request, null if not available.

getPathInfo() public method

Returns 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.

public string getPathInfo ( )
return 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() public method

Returns the port to use for insecure requests.

Defaults to 80, or the port specified by the server if the current request is insecure.

See also setPort().

public integer getPort ( )
return integer

Port number for insecure requests.

getPreferredLanguage() public method

Returns 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.

public string getPreferredLanguage ( array $languages = [] )
$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.

return string

The language that the application should use.

getQueryParam() public method

Returns the named GET parameter value.

If the GET parameter does not exist, the second parameter passed to this method will be returned.

See also getBodyParam().

public mixed getQueryParam ( $name, $defaultValue null )
$name string

The GET parameter name.

$defaultValue mixed

The default parameter value if the GET parameter does not exist.

return mixed

The GET parameter value

getQueryParams() public method

Returns the request parameters given in the $queryString.

This method will return the contents of $_GET if params where not explicitly set.

See also setQueryParams().

public array getQueryParams ( )
return array

The request GET parameter values.

getQueryString() public method

Returns part of the request URL that is after the question mark.

public string getQueryString ( )
return string

Part of the request URL that is after the question mark

getRawBody() public method

Returns the raw HTTP request body.

public string getRawBody ( )
return string

The request body

getReferrer() public method

Returns the URL referrer.

public string|null getReferrer ( )
return string|null

URL referrer, null if not available

getRemoteHost() public method (available since version 2.0.13)

Returns the host name of the other end of this connection.

This is always the next hop, any headers are ignored.

See also:

public string|null getRemoteHost ( )
return string|null

Remote host name, null if not available

getRemoteIP() public method (available since version 2.0.13)

Returns the IP on the other end of this connection.

This is always the next hop, any headers are ignored.

public string|null getRemoteIP ( )
return string|null

Remote IP address, null if not available.

getScriptFile() public method

Returns the entry script file path.

The default implementation will simply return $_SERVER['SCRIPT_FILENAME'].

public string getScriptFile ( )
return string

The entry script file path

throws yii\base\InvalidConfigException
getScriptUrl() public method

Returns the relative URL of the entry script.

The implementation of this method referenced Zend_Controller_Request_Http in Zend Framework.

public string getScriptUrl ( )
return string

The relative URL of the entry script.

throws yii\base\InvalidConfigException

if unable to determine the entry script URL

getSecureForwardedHeaderParts() protected method (available since version 2.0.31)

Returns decoded forwarded header

protected array getSecureForwardedHeaderParts ( )
getSecureForwardedHeaderTrustedPart() protected method (available since version 2.0.31)

Gets first Forwarded header value for token

protected string|null getSecureForwardedHeaderTrustedPart ( $token )
$token string

Header token

getSecureForwardedHeaderTrustedParts() protected method (available since version 2.0.31)

Gets only trusted Forwarded header parts

protected array getSecureForwardedHeaderTrustedParts ( )
getSecurePort() public method

Returns the port to use for secure requests.

Defaults to 443, or the port specified by the server if the current request is secure.

See also setSecurePort().

public integer getSecurePort ( )
return integer

Port number for secure requests.

getServerName() public method

Returns the server name.

public string getServerName ( )
return string

Server name, null if not available

getServerPort() public method

Returns the server port number.

public integer|null getServerPort ( )
return integer|null

Server port number, null if not available

getTrustedHeaders() protected method (available since version 2.0.28)

Trusted headers according to the $trustedHosts.

protected array getTrustedHeaders ( )
getUrl() public method

Returns 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.

public string getUrl ( )
return 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() public method

Returns the user agent.

public string|null getUserAgent ( )
return string|null

User agent, null if not available

getUserHost() public method

Returns the user host name.

The HOST is determined using headers and / or $_SERVER variables.

public string|null getUserHost ( )
return string|null

User host name, null if not available

getUserIP() public method

Returns the user IP address.

The IP is determined using headers and / or $_SERVER variables.

public string|null getUserIP ( )
return string|null

User IP address, null if not available

getUserIpFromIpHeader() protected method (available since version 2.0.28)

Return user IP's from IP header.

See also:

  • $getUserHost
  • $ipHeader
  • $trustedHeaders
protected string|null getUserIpFromIpHeader ( $ips )
$ips string

Comma separated IP list

return string|null

IP as string. Null is returned if IP can not be determined from header.

getUserIpFromIpHeaders() protected method (available since version 2.0.28)

Returns the user IP address from $ipHeaders.

See also $ipHeaders.

protected string|null getUserIpFromIpHeaders ( )
return string|null

User IP address, null if not available

loadCookies() protected method

Converts $_COOKIE into an array of yii\web\Cookie.

protected array loadCookies ( )
return array

The cookies obtained from request

throws yii\base\InvalidConfigException

if $cookieValidationKey is not set when $enableCookieValidation is true

loadCsrfToken() protected method

Loads the CSRF token from cookie or session.

protected string loadCsrfToken ( )
return string

The CSRF token loaded from cookie or session. Null is returned if the cookie or session does not have CSRF token.

parseAcceptHeader() public method

Parses 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],
// ]
public array parseAcceptHeader ( $header )
$header string

The header to be parsed

return array

The acceptable values ordered by their quality score. The values with the highest scores will be returned first.

post() public method

Returns POST parameter with a given name. If name isn't specified, returns an array of all POST parameters.

public array|mixed post ( $name null, $defaultValue null )
$name string

The parameter name

$defaultValue mixed

The default parameter value if the parameter does not exist.

resolve() public method

Resolves the current request into a route and the associated parameters.

public array resolve ( )
return array

The first element is the route, and the second is the associated parameters.

throws yii\web\NotFoundHttpException

if the request cannot be resolved.

resolvePathInfo() protected method

Resolves 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).

protected string resolvePathInfo ( )
return 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() protected method

Resolves 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.

protected string|boolean resolveRequestUri ( )
return string|boolean

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

setAcceptableContentTypes() public method

Sets the acceptable content types.

Please refer to getAcceptableContentTypes() on the format of the parameter.

See also:

public void setAcceptableContentTypes ( $value )
$value array

The content types that are acceptable by the end user. They should be ordered by the preference level.

setAcceptableLanguages() public method

public void setAcceptableLanguages ( $value )
$value array

The languages that are acceptable by the end user. They should be ordered by the preference level.

setBaseUrl() public method

Sets 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.

public void setBaseUrl ( $value )
$value string

The relative URL for the application

setBodyParams() public method

Sets the request body parameters.

See also:

public void setBodyParams ( $values )
$values array

The request body parameters (name-value pairs)

setHostInfo() public method

Sets 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.

See also getHostInfo() for security related notes on this property.

public void setHostInfo ( $value )
$value string|null

The schema and host part of the application URL. The trailing slashes will be removed.

setPathInfo() public method

Sets the path info of the current request.

This method is mainly provided for testing purpose.

public void setPathInfo ( $value )
$value string

The path info of the current request

setPort() public method

Sets the port to use for insecure requests.

This setter is provided in case a custom port is necessary for certain server configurations.

public void setPort ( $value )
$value integer

Port number.

setQueryParams() public method

Sets the request $queryString parameters.

See also:

public void setQueryParams ( $values )
$values array

The request query parameters (name-value pairs)

setRawBody() public method

Sets the raw HTTP request body, this method is mainly used by test scripts to simulate raw HTTP requests.

public void setRawBody ( $rawBody )
$rawBody string

The request body

setScriptFile() public method

Sets 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.

public void setScriptFile ( $value )
$value string

The entry script file path.

setScriptUrl() public method

Sets 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.

public void setScriptUrl ( $value )
$value string

The relative URL for the application entry script.

setSecurePort() public method

Sets the port to use for secure requests.

This setter is provided in case a custom port is necessary for certain server configurations.

public void setSecurePort ( $value )
$value integer

Port number.

setUrl() public method

Sets the currently requested relative URL.

The URI must refer to the portion that is after $hostInfo. Note that the URI should be URL-encoded.

public void setUrl ( $value )
$value string

The request URI to be set

validateCsrfToken() public method

Performs 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 yii\web\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.

public boolean validateCsrfToken ( $clientSuppliedToken null )
$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.

return boolean

Whether CSRF token is valid. If $enableCsrfValidation is false, this method will return true.