HumHub Documentation (unofficial)

Request extends Request
in package

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.

Tags
author

Qiang Xue qiang.xue@gmail.com

since
2.0
SuppressWarnings

(PHPMD.SuperGlobals)

Table of Contents

Constants

CSRF_HEADER  = 'X-CSRF-Token'
The name of the HTTP header for sending CSRF token.
CSRF_MASK_LENGTH  = 8
The length of the CSRF token mask.

Properties

$absoluteUrl  : string
$acceptableContentTypes  : array<string|int, mixed>
$acceptableLanguages  : array<string|int, mixed>
$authCredentials  : array<string|int, mixed>
$authPassword  : string|null
$authUser  : string|null
$baseUrl  : string
$behaviors  : array<string|int, Behavior>
$bodyParams  : array<string|int, mixed>|object
$contentType  : string
$cookies  : CookieCollection
$cookieValidationKey  : string
$csrfCookie  : array<string|int, mixed>
$csrfParam  : string
$csrfToken  : string
$csrfTokenFromHeader  : string|null
$enableCookieValidation  : bool
$enableCsrfCookie  : bool
$enableCsrfValidation  : bool
$eTags  : array<string|int, mixed>
$headers  : HeaderCollection
$hostInfo  : string|null
$hostName  : string|null
$ipHeaders  : array<string|int, string>
$isAjax  : bool
$isConsoleRequest  : bool
$isDelete  : bool
$isFlash  : bool
$isGet  : bool
$isHead  : bool
$isOptions  : bool
$isPatch  : bool
$isPjax  : bool
$isPost  : bool
$isPut  : bool
$isSecureConnection  : bool
$method  : string
$methodParam  : string
$origin  : string|null
$parsers  : array<string|int, mixed>
$pathInfo  : string
$port  : int
$portHeaders  : array<string|int, string>
$queryParams  : array<string|int, mixed>
$queryString  : string
$rawBody  : string
$referrer  : string|null
$remoteHost  : string|null
$remoteIP  : string|null
$scriptFile  : string
$scriptFile  : string
$scriptUrl  : string
$secureHeaders  : array<string|int, mixed>
$securePort  : int
$secureProtocolHeaders  : array<string|int, mixed>
$serverName  : string|null
$serverPort  : int|null
$trustedHosts  : array<string|int, mixed>
$url  : string
$userAgent  : string|null
$userHost  : string|null
$userIP  : string|null
$_baseUrl  : mixed
$_behaviors  : array<string|int, Behavior>|null
$_bodyParams  : mixed
$_contentTypes  : mixed
$_cookies  : CookieCollection
$_csrfToken  : mixed
$_events  : array<string|int, mixed>
$_eventWildcards  : array<string|int, mixed>
$_headers  : HeaderCollection
$_hostInfo  : mixed
$_hostName  : mixed
$_ip  : mixed
$_isConsoleRequest  : mixed
$_languages  : mixed
$_pathInfo  : mixed
$_port  : mixed
$_queryParams  : mixed
$_rawBody  : mixed
$_scriptFile  : mixed
$_scriptUrl  : mixed
$_secureForwardedHeaderParts  : mixed
$_secureForwardedHeaderTrustedParts  : mixed
$_securePort  : mixed
$_url  : mixed

Methods

__call()  : mixed
Calls the named method which is not a class method.
__clone()  : mixed
This method is called after the object is created by cloning an existing one.
__construct()  : mixed
Constructor.
__get()  : mixed
Returns the value of a component property.
__isset()  : bool
Checks if a property is set, i.e. defined and not null.
__set()  : mixed
Sets the value of a component property.
__unset()  : mixed
Sets a component property to be null.
attachBehavior()  : Behavior
Attaches a behavior to this component.
attachBehaviors()  : mixed
Attaches a list of behaviors to the component.
behaviors()  : array<string|int, mixed>
Returns a list of behaviors that this component should behave as.
canGetProperty()  : bool
Returns a value indicating whether a property can be read.
canSetProperty()  : bool
Returns a value indicating whether a property can be set.
className()  : string
Returns the fully qualified name of this class.
detachBehavior()  : Behavior|null
Detaches a behavior from the component.
detachBehaviors()  : mixed
Detaches all behaviors from the component.
ensureBehaviors()  : mixed
Makes sure that the behaviors declared in [[behaviors()]] are attached to this component.
get()  : array<string|int, mixed>|mixed
Returns GET parameter with a given name. If name isn't specified, returns an array of all GET parameters.
getAbsoluteUrl()  : string
Returns the currently requested absolute URL.
getAcceptableContentTypes()  : array<string|int, mixed>
Returns the content types acceptable by the end user.
getAcceptableLanguages()  : array<string|int, mixed>
Returns the languages acceptable by the end user.
getAuthCredentials()  : array<string|int, mixed>
getAuthPassword()  : string|null
getAuthUser()  : string|null
getBaseUrl()  : string
Returns the relative URL for the application.
getBehavior()  : Behavior|null
Returns the named behavior object.
getBehaviors()  : array<string|int, Behavior>
Returns all behaviors attached to this component.
getBodyParam()  : mixed
Returns the named request body parameter value.
getBodyParams()  : array<string|int, mixed>|object
Returns the request parameters given in the request body.
getContentType()  : string
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.
getCookies()  : CookieCollection
Returns the cookie collection.
getCsrfToken()  : string
Returns the token used to perform CSRF validation.
getCsrfTokenFromHeader()  : string|null
getETags()  : array<string|int, mixed>
Gets the Etags.
getHeaders()  : HeaderCollection
Returns the header collection.
getHostInfo()  : string|null
Returns the schema and host part of the current request URL.
getHostName()  : string|null
Returns the host part of the current request URL.
getIsAjax()  : bool
Returns whether this is an AJAX (XMLHttpRequest) request.
getIsConsoleRequest()  : bool
Returns a value indicating whether the current request is made via command line.
getIsDelete()  : bool
Returns whether this is a DELETE request.
getIsFlash()  : bool
Returns whether this is an Adobe Flash or Flex request.
getIsGet()  : bool
Returns whether this is a GET request.
getIsHead()  : bool
Returns whether this is a HEAD request.
getIsOptions()  : bool
Returns whether this is an OPTIONS request.
getIsPatch()  : bool
Returns whether this is a PATCH request.
getIsPjax()  : bool
Returns whether this is a PJAX request.
getIsPost()  : bool
Returns whether this is a POST request.
getIsPut()  : bool
Returns whether this is a PUT request.
getIsSecureConnection()  : bool
Return if the request is sent via secure channel (https).
getMethod()  : string
Returns the method of the current request (e.g. GET, POST, HEAD, PUT, PATCH, DELETE).
getOrigin()  : string|null
Returns the URL origin of a CORS request.
getPathInfo()  : string
Returns the path info of the currently requested URL.
getPort()  : int
Returns the port to use for insecure requests.
getPreferredLanguage()  : string
Returns the user-preferred language that should be used by this application.
getQueryParam()  : mixed
Returns the named GET parameter value.
getQueryParams()  : array<string|int, mixed>
Returns the request parameters given in the [[queryString]].
getQueryString()  : string
Returns part of the request URL that is after the question mark.
getRawBody()  : string
Returns the raw HTTP request body.
getReferrer()  : string|null
Returns the URL referrer.
getRemoteHost()  : string|null
Returns the host name of the other end of this connection.
getRemoteIP()  : string|null
Returns the IP on the other end of this connection.
getScriptFile()  : string
Returns the entry script file path.
getScriptUrl()  : string
Returns the relative URL of the entry script.
getSecurePort()  : int
Returns the port to use for secure requests.
getServerName()  : string|null
Returns the server name.
getServerPort()  : int|null
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.
getUrl()  : string
Returns the currently requested relative URL.
getUserAgent()  : string|null
Returns the user agent.
getUserHost()  : string|null
Returns the user host name.
getUserIP()  : string|null
Returns the user IP address.
hasEventHandlers()  : bool
Returns a value indicating whether there is any handler attached to the named event.
hasMethod()  : bool
Returns a value indicating whether a method is defined.
hasProperty()  : bool
Returns a value indicating whether a property is defined for this component.
init()  : mixed
Initializes the object.
off()  : bool
Detaches an existing event handler from this component.
on()  : mixed
Attaches an event handler to an event.
parseAcceptHeader()  : array<string|int, mixed>
Parses the given `Accept` (or `Accept-Language`) header.
post()  : array<string|int, mixed>|mixed
Returns POST parameter with a given name. If name isn't specified, returns an array of all POST parameters.
resolve()  : array<string|int, mixed>
Resolves the current request into a route and the associated parameters.
setAcceptableContentTypes()  : mixed
Sets the acceptable content types.
setAcceptableLanguages()  : mixed
setBaseUrl()  : mixed
Sets the relative URL for the application.
setBodyParams()  : mixed
Sets the request body parameters.
setHostInfo()  : mixed
Sets the schema and host part of the application URL.
setIsConsoleRequest()  : mixed
Sets the value indicating whether the current request is made via command line.
setPathInfo()  : mixed
Sets the path info of the current request.
setPort()  : mixed
Sets the port to use for insecure requests.
setQueryParams()  : mixed
Sets the request [[queryString]] parameters.
setRawBody()  : mixed
Sets the raw HTTP request body, this method is mainly used by test scripts to simulate raw HTTP requests.
setScriptFile()  : mixed
Sets the entry script file path.
setScriptUrl()  : mixed
Sets the relative URL for the application entry script.
setSecurePort()  : mixed
Sets the port to use for secure requests.
setUrl()  : mixed
Sets the currently requested relative URL.
trigger()  : mixed
Triggers an event.
validateCsrfToken()  : bool
Performs the CSRF validation.
createCsrfCookie()  : Cookie
Creates a cookie with a randomly generated CSRF token.
filterHeaders()  : mixed
Filters headers according to the [[trustedHosts]].
generateCsrfToken()  : string
Generates an unmasked random token used to perform CSRF validation.
getIpValidator()  : IpValidator
Creates instance of [[IpValidator]].
getSecureForwardedHeaderParts()  : array<string|int, mixed>
Returns decoded forwarded header
getSecureForwardedHeaderTrustedPart()  : string|null
Gets first `Forwarded` header value for token
getSecureForwardedHeaderTrustedParts()  : array<string|int, mixed>
Gets only trusted `Forwarded` header parts
getTrustedHeaders()  : array<string|int, mixed>
Trusted headers according to the [[trustedHosts]].
getUserIpFromIpHeader()  : string|null
Return user IP's from IP header.
getUserIpFromIpHeaders()  : string|null
Returns the user IP address from [[ipHeaders]].
loadCookies()  : array<string|int, mixed>
Converts `$_COOKIE` into an array of [[Cookie]].
loadCsrfToken()  : string|null
Loads the CSRF token from cookie or session.
resolvePathInfo()  : string
Resolves the path info part of the currently requested URL.
resolveRequestUri()  : string|bool
Resolves the request URI portion for the currently requested URL.
attachBehaviorInternal()  : Behavior
Attaches a behavior to this component.
utf8Encode()  : string
Encodes an ISO-8859-1 string to UTF-8
validateCsrfTokenInternal()  : bool
Validates CSRF token.

Constants

CSRF_HEADER

The name of the HTTP header for sending CSRF token.

public mixed CSRF_HEADER = 'X-CSRF-Token'

CSRF_MASK_LENGTH

The length of the CSRF token mask.

public mixed CSRF_MASK_LENGTH = 8
Tags
deprecated

since 2.0.12. The mask length is now equal to the token length.

Properties

$absoluteUrl read-only

public string $absoluteUrl

The currently requested absolute URL.

$acceptableContentTypes

public array<string|int, mixed> $acceptableContentTypes

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 array<string|int, mixed> $acceptableLanguages

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

$authCredentials read-only

public array<string|int, mixed> $authCredentials

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.

$authPassword read-only

public string|null $authPassword

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

$authUser read-only

public string|null $authUser

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

$baseUrl

public string $baseUrl

The relative URL for the application.

$behaviors read-only

public array<string|int, Behavior> $behaviors

List of behaviors attached to this component.

$bodyParams

public array<string|int, mixed>|object $bodyParams

The request parameters given in the request body.

$contentType read-only

public string $contentType

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

$cookieValidationKey

public string $cookieValidationKey

a secret key used for cookie validation. This property must be set if [[enableCookieValidation]] is true.

$csrfCookie

public array<string|int, mixed> $csrfCookie = ['httpOnly' => true]

the configuration for creating the CSRF [[Cookie|cookie]]. This property is used only when both [[enableCsrfValidation]] and [[enableCsrfCookie]] are true.

$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 read-only

public string $csrfToken

The token used to perform CSRF validation.

$csrfTokenFromHeader read-only

public string|null $csrfTokenFromHeader

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

$enableCookieValidation

public bool $enableCookieValidation = true

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

$enableCsrfCookie

public bool $enableCsrfCookie = true

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.

$enableCsrfValidation

public bool $enableCsrfValidation = true

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

Tags
see
Controller::enableCsrfValidation
see
https://en.wikipedia.org/wiki/Cross-site_request_forgery

$eTags read-only

public array<string|int, mixed> $eTags

The entity tags.

$hostInfo

public string|null $hostInfo

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 [[getHostInfo()]] for security related notes on this property.

$hostName read-only

public string|null $hostName

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

$ipHeaders

public array<string|int, 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.

Tags
see
trustedHosts
see
secureHeaders
since
2.0.13

$isAjax read-only

public bool $isAjax

Whether this is an AJAX (XMLHttpRequest) request.

$isConsoleRequest

public bool $isConsoleRequest

The value indicating whether the current request is made via console.

$isDelete read-only

public bool $isDelete

Whether this is a DELETE request.

$isFlash read-only

public bool $isFlash

Whether this is an Adobe Flash or Adobe Flex request.

$isGet read-only

public bool $isGet

Whether this is a GET request.

$isHead read-only

public bool $isHead

Whether this is a HEAD request.

$isOptions read-only

public bool $isOptions

Whether this is a OPTIONS request.

$isPatch read-only

public bool $isPatch

Whether this is a PATCH request.

$isPjax read-only

public bool $isPjax

Whether this is a PJAX request.

$isPost read-only

public bool $isPost

Whether this is a POST request.

$isPut read-only

public bool $isPut

Whether this is a PUT request.

$isSecureConnection read-only

public bool $isSecureConnection

If the request is sent via secure channel (https).

$method read-only

public string $method

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

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

Tags
see
getMethod()
see
getBodyParams()

$origin read-only

public string|null $origin

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

$parsers

public array<string|int, mixed> $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 [[Yii::createObject|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.

Tags
see
getBodyParams()

$pathInfo

public string $pathInfo

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.

$port

public int $port

Port number for insecure requests.

$portHeaders

public array<string|int, 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.

Tags
see
trustedHosts
see
secureHeaders
since
2.0.46

$queryParams

public array<string|int, mixed> $queryParams

The request GET parameter values.

$queryString read-only

public string $queryString

Part of the request URL that is after the question mark.

$rawBody

public string $rawBody

The request body.

$referrer read-only

public string|null $referrer

URL referrer, null if not available.

$remoteHost read-only

public string|null $remoteHost

Remote host name, null if not available.

$remoteIP read-only

public string|null $remoteIP

Remote IP address, null if not available.

$scriptFile

public string $scriptFile

Entry script file path (processed w/ realpath()).

$scriptFile

public string $scriptFile

The entry script file path.

$scriptUrl

public string $scriptUrl

The relative URL of the entry script.

$secureHeaders

public array<string|int, mixed> $secureHeaders = [ // Common: 'X-Forwarded-For', 'X-Forwarded-Host', 'X-Forwarded-Proto', 'X-Forwarded-Port', // Microsoft: 'Front-End-Https', 'X-Rewrite-Url', // ngrok: '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.

Tags
see
https://en.wikipedia.org/wiki/List_of_HTTP_header_fields
see
https://datatracker.ietf.org/doc/html/rfc7239
see
trustedHosts
since
2.0.13

$securePort

public int $securePort

Port number for secure requests.

$secureProtocolHeaders

public array<string|int, mixed> $secureProtocolHeaders = [ 'X-Forwarded-Proto' => ['https'], // Common '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.

Tags
see
trustedHosts
see
secureHeaders
since
2.0.13

$serverName read-only

public string|null $serverName

Server name, null if not available.

$serverPort read-only

public int|null $serverPort

Server port number, null if not available.

$trustedHosts

public array<string|int, mixed> $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()|IpValidator::setRanges()]] and [[IpValidator::networks]] for advanced matching.

Tags
see
secureHeaders
since
2.0.13

$url

public string $url

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

$userAgent read-only

public string|null $userAgent

User agent, null if not available.

$userHost read-only

public string|null $userHost

User host name, null if not available.

$userIP read-only

public string|null $userIP

User IP address, null if not available.

$_behaviors

private array<string|int, Behavior>|null $_behaviors

the attached behaviors (behavior name => behavior). This is null when not initialized.

$_bodyParams

private mixed $_bodyParams

$_contentTypes

private mixed $_contentTypes

$_csrfToken

private mixed $_csrfToken

$_events

private array<string|int, mixed> $_events = []

the attached event handlers (event name => handlers)

$_eventWildcards

private array<string|int, mixed> $_eventWildcards = []

the event handlers attached for wildcard patterns (event name wildcard => handlers)

Tags
since
2.0.14

$_hostInfo

private mixed $_hostInfo

$_hostName

private mixed $_hostName

$_isConsoleRequest

private mixed $_isConsoleRequest

$_languages

private mixed $_languages

$_pathInfo

private mixed $_pathInfo

$_queryParams

private mixed $_queryParams

$_scriptFile

private mixed $_scriptFile

$_scriptUrl

private mixed $_scriptUrl

$_secureForwardedHeaderParts

private mixed $_secureForwardedHeaderParts

$_secureForwardedHeaderTrustedParts

private mixed $_secureForwardedHeaderTrustedParts

$_securePort

private mixed $_securePort

Methods

__call()

Calls the named method which is not a class method.

public __call(string $name, array<string|int, mixed> $params) : mixed

This method will check if any attached behavior has the named method and will execute it if available.

Do not call this method directly as it is a PHP magic method that will be implicitly called when an unknown method is being invoked.

Parameters
$name : string

the method name

$params : array<string|int, mixed>

method parameters

Tags
throws
UnknownMethodException

when calling unknown method

Return values
mixed

the method return value

__clone()

This method is called after the object is created by cloning an existing one.

public __clone() : mixed

It removes all behaviors because they are attached to the old object.

__construct()

Constructor.

public __construct([array<string|int, mixed> $config = [] ]) : mixed

The default implementation does two things:

  • Initializes the object with the given configuration $config.
  • Call [[init()]].

If this method is overridden in a child class, it is recommended that

  • the last parameter of the constructor is a configuration array, like $config here.
  • call the parent implementation at the end of the constructor.
Parameters
$config : array<string|int, mixed> = []

name-value pairs that will be used to initialize the object properties

__get()

Returns the value of a component property.

public __get(string $name) : mixed

This method will check in the following order and act accordingly:

  • a property defined by a getter: return the getter result
  • a property of a behavior: return the behavior property value

Do not call this method directly as it is a PHP magic method that will be implicitly called when executing $value = $component->property;.

Parameters
$name : string

the property name

Tags
throws
UnknownPropertyException

if the property is not defined

throws
InvalidCallException

if the property is write-only.

see
__set()
Return values
mixed

the property value or the value of a behavior's property

__isset()

Checks if a property is set, i.e. defined and not null.

public __isset(string $name) : bool

This method will check in the following order and act accordingly:

  • a property defined by a setter: return whether the property is set
  • a property of a behavior: return whether the property is set
  • return false for non existing properties

Do not call this method directly as it is a PHP magic method that will be implicitly called when executing isset($component->property).

Parameters
$name : string

the property name or the event name

Tags
see
https://www.php.net/manual/en/function.isset.php
Return values
bool

whether the named property is set

__set()

Sets the value of a component property.

public __set(string $name, mixed $value) : mixed

This method will check in the following order and act accordingly:

  • a property defined by a setter: set the property value
  • an event in the format of "on xyz": attach the handler to the event "xyz"
  • a behavior in the format of "as xyz": attach the behavior named as "xyz"
  • a property of a behavior: set the behavior property value

Do not call this method directly as it is a PHP magic method that will be implicitly called when executing $component->property = $value;.

Parameters
$name : string

the property name or the event name

$value : mixed

the property value

Tags
throws
UnknownPropertyException

if the property is not defined

throws
InvalidCallException

if the property is read-only.

see
__get()

__unset()

Sets a component property to be null.

public __unset(string $name) : mixed

This method will check in the following order and act accordingly:

  • a property defined by a setter: set the property value to be null
  • a property of a behavior: set the property value to be null

Do not call this method directly as it is a PHP magic method that will be implicitly called when executing unset($component->property).

Parameters
$name : string

the property name

Tags
throws
InvalidCallException

if the property is read only.

see
https://www.php.net/manual/en/function.unset.php

attachBehavior()

Attaches a behavior to this component.

public attachBehavior(string $name, string|array<string|int, mixed>|Behavior $behavior) : Behavior

This method will create the behavior object based on the given configuration. After that, the behavior object will be attached to this component by calling the [[Behavior::attach()]] method.

Parameters
$name : string

the name of the behavior.

$behavior : string|array<string|int, mixed>|Behavior

the behavior configuration. This can be one of the following:

  • a [[Behavior]] object
  • a string specifying the behavior class
  • an object configuration array that will be passed to [[Yii::createObject()]] to create the behavior object.
Tags
see
detachBehavior()
Return values
Behavior

the behavior object

attachBehaviors()

Attaches a list of behaviors to the component.

public attachBehaviors(array<string|int, mixed> $behaviors) : mixed

Each behavior is indexed by its name and should be a [[Behavior]] object, a string specifying the behavior class, or an configuration array for creating the behavior.

Parameters
$behaviors : array<string|int, mixed>

list of behaviors to be attached to the component

Tags
see
attachBehavior()

behaviors()

Returns a list of behaviors that this component should behave as.

public behaviors() : array<string|int, mixed>

Child classes may override this method to specify the behaviors they want to behave as.

The return value of this method should be an array of behavior objects or configurations indexed by behavior names. A behavior configuration can be either a string specifying the behavior class or an array of the following structure:

'behaviorName' => [
    'class' => 'BehaviorClass',
    'property1' => 'value1',
    'property2' => 'value2',
]

Note that a behavior class must extend from [[Behavior]]. Behaviors can be attached using a name or anonymously. When a name is used as the array key, using this name, the behavior can later be retrieved using [[getBehavior()]] or be detached using [[detachBehavior()]]. Anonymous behaviors can not be retrieved or detached.

Behaviors declared in this method will be attached to the component automatically (on demand).

Return values
array<string|int, mixed>

the behavior configurations.

canGetProperty()

Returns a value indicating whether a property can be read.

public canGetProperty(string $name[, bool $checkVars = true ][, bool $checkBehaviors = true ]) : bool

A property can be read if:

  • the class has a getter method associated with the specified name (in this case, property name is case-insensitive);
  • the class has a member variable with the specified name (when $checkVars is true);
  • an attached behavior has a readable property of the given name (when $checkBehaviors is true).
Parameters
$name : string

the property name

$checkVars : bool = true

whether to treat member variables as properties

$checkBehaviors : bool = true

whether to treat behaviors' properties as properties of this component

Tags
see
canSetProperty()
Return values
bool

whether the property can be read

canSetProperty()

Returns a value indicating whether a property can be set.

public canSetProperty(string $name[, bool $checkVars = true ][, bool $checkBehaviors = true ]) : bool

A property can be written if:

  • the class has a setter method associated with the specified name (in this case, property name is case-insensitive);
  • the class has a member variable with the specified name (when $checkVars is true);
  • an attached behavior has a writable property of the given name (when $checkBehaviors is true).
Parameters
$name : string

the property name

$checkVars : bool = true

whether to treat member variables as properties

$checkBehaviors : bool = true

whether to treat behaviors' properties as properties of this component

Tags
see
canGetProperty()
Return values
bool

whether the property can be written

className()

Returns the fully qualified name of this class.

public static className() : string
Tags
deprecated

since 2.0.14. On PHP >=5.5, use ::class instead.

Return values
string

the fully qualified name of this class.

detachBehavior()

Detaches a behavior from the component.

public detachBehavior(string $name) : Behavior|null

The behavior's [[Behavior::detach()]] method will be invoked.

Parameters
$name : string

the behavior's name.

Return values
Behavior|null

the detached behavior. Null if the behavior does not exist.

detachBehaviors()

Detaches all behaviors from the component.

public detachBehaviors() : mixed

ensureBehaviors()

Makes sure that the behaviors declared in [[behaviors()]] are attached to this component.

public ensureBehaviors() : mixed

get()

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

public get([string $name = null ][, mixed $defaultValue = null ]) : array<string|int, mixed>|mixed
Parameters
$name : string = null

the parameter name

$defaultValue : mixed = null

the default parameter value if the parameter does not exist.

Return values
array<string|int, mixed>|mixed

getAbsoluteUrl()

Returns the currently requested absolute URL.

public getAbsoluteUrl() : string

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

Return values
string

the currently requested absolute URL.

getAcceptableContentTypes()

Returns the content types acceptable by the end user.

public getAcceptableContentTypes() : array<string|int, mixed>

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],
// ]
Return values
array<string|int, mixed>

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

Returns the languages acceptable by the end user.

public getAcceptableLanguages() : array<string|int, mixed>

This is determined by the Accept-Language HTTP header.

Return values
array<string|int, mixed>

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

getAuthCredentials()

public getAuthCredentials() : array<string|int, mixed>
Tags
see
getAuthUser()

to get only username

see
getAuthPassword()

to get only password

since
2.0.13
Return values
array<string|int, mixed>

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 getAuthPassword() : string|null
Tags
see
getAuthCredentials()

to get both username and password in one call

Return values
string|null

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

getAuthUser()

public getAuthUser() : string|null
Tags
see
getAuthCredentials()

to get both username and password in one call

Return values
string|null

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

getBaseUrl()

Returns the relative URL for the application.

public getBaseUrl() : string

This is similar to [[scriptUrl]] except that it does not include the script file name, and the ending slashes are removed.

Tags
see
setScriptUrl()
Return values
string

the relative URL for the application

getBehavior()

Returns the named behavior object.

public getBehavior(string $name) : Behavior|null
Parameters
$name : string

the behavior name

Return values
Behavior|null

the behavior object, or null if the behavior does not exist

getBehaviors()

Returns all behaviors attached to this component.

public getBehaviors() : array<string|int, Behavior>
Return values
array<string|int, Behavior>

list of behaviors attached to this component

getBodyParam()

Returns the named request body parameter value.

public getBodyParam(string $name[, mixed $defaultValue = null ]) : mixed

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

Parameters
$name : string

the parameter name

$defaultValue : mixed = null

the default parameter value if the parameter does not exist.

Tags
see
getBodyParams()
see
setBodyParams()
Return values
mixed

the parameter value

getBodyParams()

Returns the request parameters given in the request body.

public getBodyParams() : array<string|int, mixed>|object

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 [[rawBody|request body]].

Tags
throws
InvalidConfigException

if a registered parser does not implement the [[RequestParserInterface]].

see
getMethod()
see
getBodyParam()
see
setBodyParams()
Return values
array<string|int, mixed>|object

the request parameters given in the request body.

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.

public getContentType() : string

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

Tags
link

HTTP 1.1 header field definitions

Return values
string

request content-type. Empty string is returned if this information is not available.

getCookies()

Returns the cookie collection.

public getCookies() : CookieCollection

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');
Return values
CookieCollection

the cookie collection.

getCsrfToken()

Returns the token used to perform CSRF validation.

public getCsrfToken([bool $regenerate = false ]) : string

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
$regenerate : bool = false

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 values
string

the token used to perform CSRF validation.

getCsrfTokenFromHeader()

public getCsrfTokenFromHeader() : string|null
Return values
string|null

the CSRF token sent via [[CSRF_HEADER]] by browser. Null is returned if no such header is sent.

getETags()

Gets the Etags.

public getETags() : array<string|int, mixed>
Return values
array<string|int, mixed>

The entity tags

getHostInfo()

Returns the schema and host part of the current request URL.

public getHostInfo() : string|null

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 [[setHostInfo()|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 [[setHostInfo()|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.

Tags
@property

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 [[getHostInfo()]] for security related notes on this property.

see
setHostInfo()
Return values
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.

getHostName()

Returns the host part of the current request URL.

public getHostName() : string|null

Value is calculated from current [[getHostInfo()|hostInfo]] property.

Warning: The content of this value may not be reliable, dependent on the server configuration. Please refer to [[getHostInfo()]] for more information.

Tags
see
getHostInfo()
since
2.0.10
Return values
string|null

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

getIsAjax()

Returns whether this is an AJAX (XMLHttpRequest) request.

public getIsAjax() : bool

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'}
})
Return values
bool

whether this is an AJAX (XMLHttpRequest) request.

getIsConsoleRequest()

Returns a value indicating whether the current request is made via command line.

public getIsConsoleRequest() : bool
Return values
bool

the value indicating whether the current request is made via console

getIsDelete()

Returns whether this is a DELETE request.

public getIsDelete() : bool
Return values
bool

whether this is a DELETE request.

getIsFlash()

Returns whether this is an Adobe Flash or Flex request.

public getIsFlash() : bool
Return values
bool

whether this is an Adobe Flash or Adobe Flex request.

getIsGet()

Returns whether this is a GET request.

public getIsGet() : bool
Return values
bool

whether this is a GET request.

getIsHead()

Returns whether this is a HEAD request.

public getIsHead() : bool
Return values
bool

whether this is a HEAD request.

getIsOptions()

Returns whether this is an OPTIONS request.

public getIsOptions() : bool
Return values
bool

whether this is a OPTIONS request.

getIsPatch()

Returns whether this is a PATCH request.

public getIsPatch() : bool
Return values
bool

whether this is a PATCH request.

getIsPjax()

Returns whether this is a PJAX request.

public getIsPjax() : bool
Return values
bool

whether this is a PJAX request

getIsPost()

Returns whether this is a POST request.

public getIsPost() : bool
Return values
bool

whether this is a POST request.

getIsPut()

Returns whether this is a PUT request.

public getIsPut() : bool
Return values
bool

whether this is a PUT request.

getIsSecureConnection()

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

public getIsSecureConnection() : bool
Return values
bool

if the request is sent via secure channel (https)

getMethod()

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

public getMethod() : string
Return values
string

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

getOrigin()

Returns the URL origin of a CORS request.

public getOrigin() : string|null

The return value is taken from the Origin [[getHeaders()|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.

Tags
see
getHeaders()
since
2.0.13
Return values
string|null

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

getPathInfo()

Returns the path info of the currently requested URL.

public getPathInfo() : string

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.

Tags
throws
InvalidConfigException

if the path info cannot be determined due to unexpected server configuration

Return values
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.

getPort()

Returns the port to use for insecure requests.

public getPort() : int

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

Tags
see
setPort()
Return values
int

port number for insecure requests.

getPreferredLanguage()

Returns the user-preferred language that should be used by this application.

public getPreferredLanguage([array<string|int, mixed> $languages = [] ]) : string

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
$languages : array<string|int, mixed> = []

a list of the languages supported by the application. If this is empty, the current application language will be returned without further processing.

Return values
string

the language that the application should use.

getQueryParam()

Returns the named GET parameter value.

public getQueryParam(string $name[, mixed $defaultValue = null ]) : mixed

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

Parameters
$name : string

the GET parameter name.

$defaultValue : mixed = null

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

Tags
see
getBodyParam()
Return values
mixed

the GET parameter value

getQueryParams()

Returns the request parameters given in the [[queryString]].

public getQueryParams() : array<string|int, mixed>

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

Tags
see
setQueryParams()
Return values
array<string|int, mixed>

the request GET parameter values.

getQueryString()

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

public getQueryString() : string
Return values
string

part of the request URL that is after the question mark

getRawBody()

Returns the raw HTTP request body.

public getRawBody() : string
Return values
string

the request body

getReferrer()

Returns the URL referrer.

public getReferrer() : string|null
Return values
string|null

URL referrer, null if not available

getRemoteHost()

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

public getRemoteHost() : string|null

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

Tags
see
getUserHost()
see
getRemoteIP()
since
2.0.13
Return values
string|null

remote host name, null if not available

getRemoteIP()

Returns the IP on the other end of this connection.

public getRemoteIP() : string|null

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

Tags
since
2.0.13
Return values
string|null

remote IP address, null if not available.

getScriptFile()

Returns the entry script file path.

public getScriptFile() : string

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

Tags
throws
InvalidConfigException
Return values
string

the entry script file path

getScriptUrl()

Returns the relative URL of the entry script.

public getScriptUrl() : string

The implementation of this method referenced Zend_Controller_Request_Http in Zend Framework.

Tags
throws
InvalidConfigException

if unable to determine the entry script URL

Return values
string

the relative URL of the entry script.

getSecurePort()

Returns the port to use for secure requests.

public getSecurePort() : int

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

Tags
see
setSecurePort()
Return values
int

port number for secure requests.

getServerName()

Returns the server name.

public getServerName() : string|null
Return values
string|null

server name, null if not available

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.

public getServerPort() : int|null
Tags
see
portHeaders
Return values
int|null

server port number, null if not available

getUrl()

Returns the currently requested relative URL.

public getUrl() : string

This refers to the portion of the URL that is after the [[hostInfo]] part. It includes the [[queryString]] part if any.

Tags
throws
InvalidConfigException

if the URL cannot be determined due to unusual server configuration

Return values
string

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

getUserAgent()

Returns the user agent.

public getUserAgent() : string|null
Return values
string|null

user agent, null if not available

getUserHost()

Returns the user host name.

public getUserHost() : string|null

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

Return values
string|null

user host name, null if not available

getUserIP()

Returns the user IP address.

public getUserIP() : string|null

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

Return values
string|null

user IP address, null if not available

hasEventHandlers()

Returns a value indicating whether there is any handler attached to the named event.

public hasEventHandlers(string $name) : bool
Parameters
$name : string

the event name

Return values
bool

whether there is any handler attached to the event.

hasMethod()

Returns a value indicating whether a method is defined.

public hasMethod(string $name[, bool $checkBehaviors = true ]) : bool

A method is defined if:

  • the class has a method with the specified name
  • an attached behavior has a method with the given name (when $checkBehaviors is true).
Parameters
$name : string

the property name

$checkBehaviors : bool = true

whether to treat behaviors' methods as methods of this component

Return values
bool

whether the method is defined

hasProperty()

Returns a value indicating whether a property is defined for this component.

public hasProperty(string $name[, bool $checkVars = true ][, bool $checkBehaviors = true ]) : bool

A property is defined if:

  • the class has a getter or setter method associated with the specified name (in this case, property name is case-insensitive);
  • the class has a member variable with the specified name (when $checkVars is true);
  • an attached behavior has a property of the given name (when $checkBehaviors is true).
Parameters
$name : string

the property name

$checkVars : bool = true

whether to treat member variables as properties

$checkBehaviors : bool = true

whether to treat behaviors' properties as properties of this component

Tags
see
canGetProperty()
see
canSetProperty()
Return values
bool

whether the property is defined

init()

Initializes the object.

public init() : mixed

This method is invoked at the end of the constructor after the object is initialized with the given configuration.

off()

Detaches an existing event handler from this component.

public off(string $name[, callable|null $handler = null ]) : bool

This method is the opposite of [[on()]].

Note: in case wildcard pattern is passed for event name, only the handlers registered with this wildcard will be removed, while handlers registered with plain names matching this wildcard will remain.

Parameters
$name : string

event name

$handler : callable|null = null

the event handler to be removed. If it is null, all handlers attached to the named event will be removed.

Tags
see
on()
Return values
bool

if a handler is found and detached

on()

Attaches an event handler to an event.

public on(string $name, callable $handler[, mixed $data = null ][, bool $append = true ]) : mixed

The event handler must be a valid PHP callback. The following are some examples:

function ($event) { ... }         // anonymous function
[$object, 'handleClick']          // $object->handleClick()
['Page', 'handleClick']           // Page::handleClick()
'handleClick'                     // global function handleClick()

The event handler must be defined with the following signature,

function ($event)

where $event is an [[Event]] object which includes parameters associated with the event.

Since 2.0.14 you can specify event name as a wildcard pattern:

$component->on('event.group.*', function ($event) {
    Yii::trace($event->name . ' is triggered.');
});
Parameters
$name : string

the event name

$handler : callable

the event handler

$data : mixed = null

the data to be passed to the event handler when the event is triggered. When the event handler is invoked, this data can be accessed via [[Event::data]].

$append : bool = true

whether to append new event handler to the end of the existing handler list. If false, the new handler will be inserted at the beginning of the existing handler list.

Tags
see
off()

parseAcceptHeader()

Parses the given `Accept` (or `Accept-Language`) header.

public parseAcceptHeader(string $header) : array<string|int, mixed>

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
$header : string

the header to be parsed

Return values
array<string|int, mixed>

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

post()

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

public post([string $name = null ][, mixed $defaultValue = null ]) : array<string|int, mixed>|mixed
Parameters
$name : string = null

the parameter name

$defaultValue : mixed = null

the default parameter value if the parameter does not exist.

Return values
array<string|int, mixed>|mixed

resolve()

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

public resolve() : array<string|int, mixed>
Tags
throws
NotFoundHttpException

if the request cannot be resolved.

Return values
array<string|int, mixed>

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

setAcceptableContentTypes()

Sets the acceptable content types.

public setAcceptableContentTypes(array<string|int, mixed> $value) : mixed

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

Parameters
$value : array<string|int, mixed>

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

Tags
see
getAcceptableContentTypes()
see
parseAcceptHeader()

setAcceptableLanguages()

public setAcceptableLanguages(array<string|int, mixed> $value) : mixed
Parameters
$value : array<string|int, mixed>

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

setBaseUrl()

Sets the relative URL for the application.

public setBaseUrl(string $value) : mixed

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
$value : string

the relative URL for the application

setBodyParams()

Sets the request body parameters.

public setBodyParams(array<string|int, mixed>|object $values) : mixed
Parameters
$values : array<string|int, mixed>|object

the request body parameters (name-value pairs)

Tags
see
getBodyParams()

setHostInfo()

Sets the schema and host part of the application URL.

public setHostInfo(string|null $value) : mixed

This setter is provided in case the schema and hostname cannot be determined on certain Web servers.

Parameters
$value : string|null

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

Tags
see
getHostInfo()

for security related notes on this property.

setIsConsoleRequest()

Sets the value indicating whether the current request is made via command line.

public setIsConsoleRequest(bool $value) : mixed
Parameters
$value : bool

the value indicating whether the current request is made via command line

setPathInfo()

Sets the path info of the current request.

public setPathInfo(string $value) : mixed

This method is mainly provided for testing purpose.

Parameters
$value : string

the path info of the current request

setPort()

Sets the port to use for insecure requests.

public setPort(int $value) : mixed

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

Parameters
$value : int

port number.

setQueryParams()

Sets the request [[queryString]] parameters.

public setQueryParams(array<string|int, mixed> $values) : mixed
Parameters
$values : array<string|int, mixed>

the request query parameters (name-value pairs)

Tags
see
getQueryParam()
see
getQueryParams()

setRawBody()

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

public setRawBody(string $rawBody) : mixed
Parameters
$rawBody : string

the request body

setScriptFile()

Sets the entry script file path.

public setScriptFile(string $value) : mixed

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
$value : string

the entry script file path.

setScriptUrl()

Sets the relative URL for the application entry script.

public setScriptUrl(string $value) : mixed

This setter is provided in case the entry script URL cannot be determined on certain Web servers.

Parameters
$value : string

the relative URL for the application entry script.

setSecurePort()

Sets the port to use for secure requests.

public setSecurePort(int $value) : mixed

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

Parameters
$value : int

port number.

setUrl()

Sets the currently requested relative URL.

public setUrl(string $value) : mixed

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

Parameters
$value : string

the request URI to be set

trigger()

Triggers an event.

public trigger(string $name[, Event|null $event = null ]) : mixed

This method represents the happening of an event. It invokes all attached handlers for the event including class-level handlers.

Parameters
$name : string

the event name

$event : Event|null = null

the event instance. If not set, a default [[Event]] object will be created.

validateCsrfToken()

Performs the CSRF validation.

public validateCsrfToken([string|null $clientSuppliedToken = null ]) : bool

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
$clientSuppliedToken : string|null = null

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 values
bool

whether CSRF token is valid. If [[enableCsrfValidation]] is false, this method will return true.

createCsrfCookie()

Creates a cookie with a randomly generated CSRF token.

protected createCsrfCookie(string $token) : Cookie

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

Parameters
$token : string

the CSRF token

Tags
see
enableCsrfValidation
Return values
Cookie

the generated cookie

filterHeaders()

Filters headers according to the [[trustedHosts]].

protected filterHeaders(HeaderCollection $headerCollection) : mixed
Parameters
$headerCollection : HeaderCollection
Tags
since
2.0.13

generateCsrfToken()

Generates an unmasked random token used to perform CSRF validation.

protected generateCsrfToken() : string
Return values
string

the random token for CSRF validation.

getIpValidator()

Creates instance of [[IpValidator]].

protected getIpValidator() : IpValidator

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

Tags
since
2.0.13
Return values
IpValidator

getSecureForwardedHeaderParts()

Returns decoded forwarded header

protected getSecureForwardedHeaderParts() : array<string|int, mixed>
Tags
since
2.0.31
Return values
array<string|int, mixed>

getSecureForwardedHeaderTrustedPart()

Gets first `Forwarded` header value for token

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

Header token

Tags
since
2.0.31
Return values
string|null

getSecureForwardedHeaderTrustedParts()

Gets only trusted `Forwarded` header parts

protected getSecureForwardedHeaderTrustedParts() : array<string|int, mixed>
Tags
since
2.0.31
Return values
array<string|int, mixed>

getTrustedHeaders()

Trusted headers according to the [[trustedHosts]].

protected getTrustedHeaders() : array<string|int, mixed>
Tags
since
2.0.28
Return values
array<string|int, mixed>

getUserIpFromIpHeader()

Return user IP's from IP header.

protected getUserIpFromIpHeader(string $ips) : string|null
Parameters
$ips : string

comma separated IP list

Tags
see
getUserHost()
see
ipHeaders
see
getTrustedHeaders()
since
2.0.28
Return values
string|null

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

getUserIpFromIpHeaders()

Returns the user IP address from [[ipHeaders]].

protected getUserIpFromIpHeaders() : string|null
Tags
see
ipHeaders
since
2.0.28
Return values
string|null

user IP address, null if not available

loadCookies()

Converts `$_COOKIE` into an array of [[Cookie]].

protected loadCookies() : array<string|int, mixed>
Tags
throws
InvalidConfigException

if [[cookieValidationKey]] is not set when [[enableCookieValidation]] is true

Return values
array<string|int, mixed>

the cookies obtained from request

loadCsrfToken()

Loads the CSRF token from cookie or session.

protected loadCsrfToken() : string|null
Return values
string|null

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

resolvePathInfo()

Resolves the path info part of the currently requested URL.

protected resolvePathInfo() : string

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

Tags
throws
InvalidConfigException

if the path info cannot be determined due to unexpected server configuration

Return values
string

part of the request URL that is after the entry script and before the question mark. Note, the returned path info is decoded.

resolveRequestUri()

Resolves the request URI portion for the currently requested URL.

protected resolveRequestUri() : string|bool

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.

Tags
throws
InvalidConfigException

if the request URI cannot be determined due to unusual server configuration

Return values
string|bool

the request URI portion for the currently requested URL. Note that the URI returned may be URL-encoded depending on the client.

attachBehaviorInternal()

Attaches a behavior to this component.

private attachBehaviorInternal(string|int $name, string|array<string|int, mixed>|Behavior $behavior) : Behavior
Parameters
$name : string|int

the name of the behavior. If this is an integer, it means the behavior is an anonymous one. Otherwise, the behavior is a named one and any existing behavior with the same name will be detached first.

$behavior : string|array<string|int, mixed>|Behavior

the behavior to be attached

Return values
Behavior

the attached behavior.

utf8Encode()

Encodes an ISO-8859-1 string to UTF-8

private utf8Encode(string $s) : string
Parameters
$s : string
Tags
see
https://github.com/symfony/polyfill-php72/blob/master/Php72.php#L24
phpcs:disable

Generic.Formatting.DisallowMultipleStatements.SameLine

phpcs:disable

Squiz.WhiteSpace.ScopeClosingBrace.ContentBefore

Return values
string

the UTF-8 translation of s.

validateCsrfTokenInternal()

Validates CSRF token.

private validateCsrfTokenInternal(string $clientSuppliedToken, string $trueToken) : bool
Parameters
$clientSuppliedToken : string

The masked client-supplied token.

$trueToken : string

The masked true token.

Return values
bool

        
On this page

Search results