Class yii\web\Request
Inheritance | yii\web\Request » yii\base\Request » yii\base\Component » yii\base\BaseObject |
---|---|
Implements | yii\base\Configurable |
Available since version | 2.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
Property | Type | Description | Defined By |
---|---|---|---|
$absoluteUrl | string | The currently requested absolute URL. | yii\web\Request |
$acceptableContentTypes | array | The content types ordered by the quality score. | yii\web\Request |
$acceptableLanguages | array | The languages ordered by the preference level. | 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. |
yii\web\Request |
$authPassword | string|null | The password sent via HTTP authentication, null if the password is not given. |
yii\web\Request |
$authUser | string|null | The username sent via HTTP authentication, null if the username is not given. |
yii\web\Request |
$baseUrl | string | The relative URL for the application. | yii\web\Request |
$behaviors | yii\base\Behavior[] | List of behaviors attached to this component. | yii\base\Component |
$bodyParams | array|object | The request parameters given in the request body. | yii\web\Request |
$contentType | string | Request content-type. | yii\web\Request |
$cookieValidationKey | string | A secret key used for cookie validation. | yii\web\Request |
$cookies | yii\web\CookieCollection | The cookie collection. | 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. | yii\web\Request |
$csrfTokenFromHeader | string|null | The CSRF token sent via CSRF_HEADER by browser. | yii\web\Request |
$eTags | array | The entity tags. | 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. | yii\web\Request |
$hostInfo | 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. |
yii\web\Request |
$hostName | string|null | Hostname part of the request URL (e.g. www.yiiframework.com ). |
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. | 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. | yii\web\Request |
$isFlash | boolean | Whether this is an Adobe Flash or Adobe Flex request. | yii\web\Request |
$isGet | boolean | Whether this is a GET request. | yii\web\Request |
$isHead | boolean | Whether this is a HEAD request. | yii\web\Request |
$isOptions | boolean | Whether this is a OPTIONS request. | yii\web\Request |
$isPatch | boolean | Whether this is a PATCH request. | yii\web\Request |
$isPjax | boolean | Whether this is a PJAX request. | yii\web\Request |
$isPost | boolean | Whether this is a POST request. | yii\web\Request |
$isPut | boolean | Whether this is a PUT request. | yii\web\Request |
$isSecureConnection | boolean | If the request is sent via secure channel (https). | yii\web\Request |
$method | string | Request method, such as GET, POST, HEAD, PUT, PATCH, DELETE. | 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. |
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. | yii\web\Request |
$port | integer | Port number for insecure requests. | yii\web\Request |
$portHeaders | string[] | List of headers where proxies store the real request port. | 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. | yii\web\Request |
$rawBody | string | The request body. | yii\web\Request |
$referrer | string|null | URL referrer, null if not available. | yii\web\Request |
$remoteHost | string|null | Remote host name, null if not available. |
yii\web\Request |
$remoteIP | string|null | Remote IP address, null if not available. |
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|null | Server name, null if not available. | yii\web\Request |
$serverPort | integer|null | Server port number, null if not available. | yii\web\Request |
$trustedHosts | array | The configuration for trusted security related headers. | yii\web\Request |
$url | string | The currently requested relative URL. | yii\web\Request |
$userAgent | string|null | User agent, null if not available. | yii\web\Request |
$userHost | string|null | User host name, null if not available. | yii\web\Request |
$userIP | string|null | User IP address, null if not available. | yii\web\Request |
Public Methods
Method | Description | Defined By |
---|---|---|
__call() | Calls the named method which is not a class method. | yii\base\Component |
__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 a component property. | yii\base\Component |
__isset() | Checks if a property is set, i.e. defined and not null. | yii\base\Component |
__set() | Sets the value of a component property. | yii\base\Component |
__unset() | Sets a component property to be null. | yii\base\Component |
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\Component |
canSetProperty() | Returns a value indicating whether a property can be set. | yii\base\Component |
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. 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. | 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\Component |
hasProperty() | Returns a value indicating whether a property is defined for this component. | yii\base\Component |
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
Method | Description | Defined 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
Constant | Value | Description | Defined 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
The currently requested absolute URL.
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.
The languages ordered by the preference level. The first element represents the most preferred language.
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.
The password sent via HTTP authentication, null
if the password
is not given.
The username sent via HTTP authentication, null
if the username is
not given.
The request parameters given in the request body.
Request content-type. Empty string is returned if this information is not available.
The configuration for creating the CSRF cookie. This property is used only when both $enableCsrfValidation and $enableCsrfCookie are true.
The name of the token used to prevent CSRF. Defaults to '_csrf'. This property is used only when $enableCsrfValidation is true.
The token used to perform CSRF validation.
The CSRF token sent via CSRF_HEADER by browser. Null is returned if no such header is sent.
Whether cookies should be validated to ensure they are not tampered. Defaults to 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.
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:
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 part of the request URL (e.g. www.yiiframework.com
).
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:
Whether this is an AJAX (XMLHttpRequest) request.
Whether this is an Adobe Flash or Adobe Flex request.
If the request is sent via secure channel (https).
Request method, such as GET, POST, HEAD, PUT, PATCH, DELETE. The value returned is turned into upper case.
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:
URL origin of a CORS request, null
if not available.
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().
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.
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.
See also:
The language that the application should use.
Part of the request URL that is after the question mark.
Remote host name, null
if not available.
Remote IP address, null
if not available.
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:
'X-Forwarded-For',
'X-Forwarded-Host',
'X-Forwarded-Proto',
'X-Forwarded-Port',
'Front-End-Https',
'X-Rewrite-Url',
'X-Original-Host',
]
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:
'X-Forwarded-Proto' => [
'https',
],
'Front-End-Https' => [
'on',
],
]
Server name, null if not available.
Server port number, null if not available.
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.
The currently requested relative URL. Note that the URI returned may be URL-encoded depending on the client.
User host name, null if not available.
Method Details
Defined in: yii\base\Component::__call()
Calls the named method which is not a class method.
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.
public mixed __call ( $name, $params ) | ||
$name | string |
The method name |
$params | array |
Method parameters |
return | mixed |
The method return value |
---|---|---|
throws | yii\base\UnknownMethodException |
when calling unknown method |
public function __call($name, $params)
{
$this->ensureBehaviors();
foreach ($this->_behaviors as $object) {
if ($object->hasMethod($name)) {
return call_user_func_array([$object, $name], $params);
}
}
throw new UnknownMethodException('Calling unknown method: ' . get_class($this) . "::$name()");
}
Defined in: yii\base\Component::__clone()
This method is called after the object is created by cloning an existing one.
It removes all behaviors because they are attached to the old object.
public void __clone ( ) |
public function __clone()
{
$this->_events = [];
$this->_eventWildcards = [];
$this->_behaviors = null;
}
Defined in: yii\base\BaseObject::__construct()
Constructor.
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.
public void __construct ( $config = [] ) | ||
$config | array |
Name-value pairs that will be used to initialize the object properties |
public function __construct($config = [])
{
if (!empty($config)) {
Yii::configure($this, $config);
}
$this->init();
}
Defined in: yii\base\Component::__get()
Returns the value of a component property.
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;
.
See also __set().
public mixed __get ( $name ) | ||
$name | string |
The property name |
return | mixed |
The property value or the value of a behavior's property |
---|---|---|
throws | yii\base\UnknownPropertyException |
if the property is not defined |
throws | yii\base\InvalidCallException |
if the property is write-only. |
public function __get($name)
{
$getter = 'get' . $name;
if (method_exists($this, $getter)) {
// read property, e.g. getName()
return $this->$getter();
}
// behavior property
$this->ensureBehaviors();
foreach ($this->_behaviors as $behavior) {
if ($behavior->canGetProperty($name)) {
return $behavior->$name;
}
}
if (method_exists($this, 'set' . $name)) {
throw new InvalidCallException('Getting write-only property: ' . get_class($this) . '::' . $name);
}
throw new UnknownPropertyException('Getting unknown property: ' . get_class($this) . '::' . $name);
}
Defined in: yii\base\Component::__isset()
Checks if a property is set, i.e. defined and not null.
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)
.
public boolean __isset ( $name ) | ||
$name | string |
The property name or the event name |
return | boolean |
Whether the named property is set |
---|
public function __isset($name)
{
$getter = 'get' . $name;
if (method_exists($this, $getter)) {
return $this->$getter() !== null;
}
// behavior property
$this->ensureBehaviors();
foreach ($this->_behaviors as $behavior) {
if ($behavior->canGetProperty($name)) {
return $behavior->$name !== null;
}
}
return false;
}
Defined in: yii\base\Component::__set()
Sets the value of a component property.
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;
.
See also __get().
public void __set ( $name, $value ) | ||
$name | string |
The property name or the event name |
$value | mixed |
The property value |
throws | yii\base\UnknownPropertyException |
if the property is not defined |
---|---|---|
throws | yii\base\InvalidCallException |
if the property is read-only. |
public function __set($name, $value)
{
$setter = 'set' . $name;
if (method_exists($this, $setter)) {
// set property
$this->$setter($value);
return;
} elseif (strncmp($name, 'on ', 3) === 0) {
// on event: attach event handler
$this->on(trim(substr($name, 3)), $value);
return;
} elseif (strncmp($name, 'as ', 3) === 0) {
// as behavior: attach behavior
$name = trim(substr($name, 3));
$this->attachBehavior($name, $value instanceof Behavior ? $value : Yii::createObject($value));
return;
}
// behavior property
$this->ensureBehaviors();
foreach ($this->_behaviors as $behavior) {
if ($behavior->canSetProperty($name)) {
$behavior->$name = $value;
return;
}
}
if (method_exists($this, 'get' . $name)) {
throw new InvalidCallException('Setting read-only property: ' . get_class($this) . '::' . $name);
}
throw new UnknownPropertyException('Setting unknown property: ' . get_class($this) . '::' . $name);
}
Defined in: yii\base\Component::__unset()
Sets a component property to be null.
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)
.
public void __unset ( $name ) | ||
$name | string |
The property name |
throws | yii\base\InvalidCallException |
if the property is read only. |
---|
public function __unset($name)
{
$setter = 'set' . $name;
if (method_exists($this, $setter)) {
$this->$setter(null);
return;
}
// behavior property
$this->ensureBehaviors();
foreach ($this->_behaviors as $behavior) {
if ($behavior->canSetProperty($name)) {
$behavior->$name = null;
return;
}
}
throw new InvalidCallException('Unsetting an unknown or read-only property: ' . get_class($this) . '::' . $name);
}
Defined in: yii\base\Component::attachBehavior()
Attaches a behavior to this component.
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 yii\base\Behavior::attach() method.
See also detachBehavior().
public yii\base\Behavior attachBehavior ( $name, $behavior ) | ||
$name | string |
The name of the behavior. |
$behavior | string|array|yii\base\Behavior |
The behavior configuration. This can be one of the following:
|
return | yii\base\Behavior |
The behavior object |
---|
public function attachBehavior($name, $behavior)
{
$this->ensureBehaviors();
return $this->attachBehaviorInternal($name, $behavior);
}
Defined in: yii\base\Component::attachBehaviors()
Attaches a list of behaviors to the component.
Each behavior is indexed by its name and should be a yii\base\Behavior object, a string specifying the behavior class, or an configuration array for creating the behavior.
See also attachBehavior().
public void attachBehaviors ( $behaviors ) | ||
$behaviors | array |
List of behaviors to be attached to the component |
public function attachBehaviors($behaviors)
{
$this->ensureBehaviors();
foreach ($behaviors as $name => $behavior) {
$this->attachBehaviorInternal($name, $behavior);
}
}
Defined in: yii\base\Component::behaviors()
Returns a list of behaviors that this component should behave as.
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 yii\base\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).
public array behaviors ( ) | ||
return | array |
The behavior configurations. |
---|
public function behaviors()
{
return [];
}
Defined in: yii\base\Component::canGetProperty()
Returns a value indicating whether a property can be read.
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).
See also canSetProperty().
public boolean canGetProperty ( $name, $checkVars = true, $checkBehaviors = true ) | ||
$name | string |
The property name |
$checkVars | boolean |
Whether to treat member variables as properties |
$checkBehaviors | boolean |
Whether to treat behaviors' properties as properties of this component |
return | boolean |
Whether the property can be read |
---|
public function canGetProperty($name, $checkVars = true, $checkBehaviors = true)
{
if (method_exists($this, 'get' . $name) || $checkVars && property_exists($this, $name)) {
return true;
} elseif ($checkBehaviors) {
$this->ensureBehaviors();
foreach ($this->_behaviors as $behavior) {
if ($behavior->canGetProperty($name, $checkVars)) {
return true;
}
}
}
return false;
}
Defined in: yii\base\Component::canSetProperty()
Returns a value indicating whether a property can be set.
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).
See also canGetProperty().
public boolean canSetProperty ( $name, $checkVars = true, $checkBehaviors = true ) | ||
$name | string |
The property name |
$checkVars | boolean |
Whether to treat member variables as properties |
$checkBehaviors | boolean |
Whether to treat behaviors' properties as properties of this component |
return | boolean |
Whether the property can be written |
---|
public function canSetProperty($name, $checkVars = true, $checkBehaviors = true)
{
if (method_exists($this, 'set' . $name) || $checkVars && property_exists($this, $name)) {
return true;
} elseif ($checkBehaviors) {
$this->ensureBehaviors();
foreach ($this->_behaviors as $behavior) {
if ($behavior->canSetProperty($name, $checkVars)) {
return true;
}
}
}
return false;
}
::class
instead.
Defined in: yii\base\BaseObject::className()
Returns the fully qualified name of this class.
public static string className ( ) | ||
return | string |
The fully qualified name of this class. |
---|
public static function className()
{
return get_called_class();
}
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 |
---|
protected function createCsrfCookie($token)
{
$options = $this->csrfCookie;
return Yii::createObject(array_merge($options, [
'class' => 'yii\web\Cookie',
'name' => $this->csrfParam,
'value' => $token,
]));
}
Defined in: yii\base\Component::detachBehavior()
Detaches a behavior from the component.
The behavior's yii\base\Behavior::detach() method will be invoked.
public yii\base\Behavior|null detachBehavior ( $name ) | ||
$name | string |
The behavior's name. |
return | yii\base\Behavior|null |
The detached behavior. Null if the behavior does not exist. |
---|
public function detachBehavior($name)
{
$this->ensureBehaviors();
if (isset($this->_behaviors[$name])) {
$behavior = $this->_behaviors[$name];
unset($this->_behaviors[$name]);
$behavior->detach();
return $behavior;
}
return null;
}
Defined in: yii\base\Component::detachBehaviors()
Detaches all behaviors from the component.
public void detachBehaviors ( ) |
public function detachBehaviors()
{
$this->ensureBehaviors();
foreach ($this->_behaviors as $name => $behavior) {
$this->detachBehavior($name);
}
}
Defined in: yii\base\Component::ensureBehaviors()
Makes sure that the behaviors declared in behaviors() are attached to this component.
public void ensureBehaviors ( ) |
public function ensureBehaviors()
{
if ($this->_behaviors === null) {
$this->_behaviors = [];
foreach ($this->behaviors() as $name => $behavior) {
$this->attachBehaviorInternal($name, $behavior);
}
}
}
Filters headers according to the $trustedHosts.
protected void filterHeaders ( yii\web\HeaderCollection $headerCollection ) | ||
$headerCollection | yii\web\HeaderCollection |
protected function filterHeaders(HeaderCollection $headerCollection)
{
$trustedHeaders = $this->getTrustedHeaders();
// remove all secure headers unless they are trusted
foreach ($this->secureHeaders as $secureHeader) {
if (!in_array($secureHeader, $trustedHeaders)) {
$headerCollection->remove($secureHeader);
}
}
}
Generates an unmasked random token used to perform CSRF validation.
protected string generateCsrfToken ( ) | ||
return | string |
The random token for CSRF validation. |
---|
protected function generateCsrfToken()
{
$token = Yii::$app->getSecurity()->generateRandomString();
if ($this->enableCsrfCookie) {
$cookie = $this->createCsrfCookie($token);
Yii::$app->getResponse()->getCookies()->add($cookie);
} else {
Yii::$app->getSession()->set($this->csrfParam, $token);
}
return $token;
}
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. |
public function get($name = null, $defaultValue = null)
{
if ($name === null) {
return $this->getQueryParams();
}
return $this->getQueryParam($name, $defaultValue);
}
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. |
---|
public function getAbsoluteUrl()
{
return $this->getHostInfo() . $this->getUrl();
}
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. |
---|
public function getAcceptableContentTypes()
{
if ($this->_contentTypes === null) {
if ($this->headers->get('Accept') !== null) {
$this->_contentTypes = $this->parseAcceptHeader($this->headers->get('Accept'));
} else {
$this->_contentTypes = [];
}
}
return $this->_contentTypes;
}
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. |
---|
public function getAcceptableLanguages()
{
if ($this->_languages === null) {
if ($this->headers->has('Accept-Language')) {
$this->_languages = array_keys($this->parseAcceptHeader($this->headers->get('Accept-Language')));
} else {
$this->_languages = [];
}
}
return $this->_languages;
}
public array getAuthCredentials ( ) | ||
return | array |
That contains exactly two elements:
|
---|
public function getAuthCredentials()
{
$username = isset($_SERVER['PHP_AUTH_USER']) ? $_SERVER['PHP_AUTH_USER'] : null;
$password = isset($_SERVER['PHP_AUTH_PW']) ? $_SERVER['PHP_AUTH_PW'] : null;
if ($username !== null || $password !== null) {
return [$username, $password];
}
/**
* Apache with php-cgi does not pass HTTP Basic authentication to PHP by default.
* To make it work, add one of the following lines to to your .htaccess file:
*
* SetEnvIf Authorization .+ HTTP_AUTHORIZATION=$0
* --OR--
* RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
*/
$auth_token = $this->getHeaders()->get('Authorization');
if ($auth_token !== null && strncasecmp($auth_token, 'basic', 5) === 0) {
$parts = array_map(function ($value) {
return strlen($value) === 0 ? null : $value;
}, explode(':', base64_decode(mb_substr($auth_token, 6)), 2));
if (count($parts) < 2) {
return [$parts[0], null];
}
return $parts;
}
return [null, null];
}
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, |
---|
public function getAuthPassword()
{
return $this->getAuthCredentials()[1];
}
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, |
---|
public function getAuthUser()
{
return $this->getAuthCredentials()[0];
}
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 |
---|
public function getBaseUrl()
{
if ($this->_baseUrl === null) {
$this->_baseUrl = rtrim(dirname($this->getScriptUrl()), '\\/');
}
return $this->_baseUrl;
}
Defined in: yii\base\Component::getBehavior()
Returns the named behavior object.
public yii\base\Behavior|null getBehavior ( $name ) | ||
$name | string |
The behavior name |
return | yii\base\Behavior|null |
The behavior object, or null if the behavior does not exist |
---|
public function getBehavior($name)
{
$this->ensureBehaviors();
return isset($this->_behaviors[$name]) ? $this->_behaviors[$name] : null;
}
Defined in: yii\base\Component::getBehaviors()
Returns all behaviors attached to this component.
public yii\base\Behavior[] getBehaviors ( ) | ||
return | yii\base\Behavior[] |
List of behaviors attached to this component |
---|
public function getBehaviors()
{
$this->ensureBehaviors();
return $this->_behaviors;
}
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 |
---|
public function getBodyParam($name, $defaultValue = null)
{
$params = $this->getBodyParams();
if (is_object($params)) {
// unable to use `ArrayHelper::getValue()` due to different dots in key logic and lack of exception handling
try {
return isset($params->{$name}) ? $params->{$name} : $defaultValue;
} catch (\Exception $e) {
return $defaultValue;
}
}
return isset($params[$name]) ? $params[$name] : $defaultValue;
}
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|object getBodyParams ( ) | ||
return | array|object |
The request parameters given in the request body. |
---|---|---|
throws | yii\base\InvalidConfigException |
if a registered parser does not implement the yii\web\RequestParserInterface. |
public function getBodyParams()
{
if ($this->_bodyParams === null) {
if (isset($_POST[$this->methodParam])) {
$this->_bodyParams = $_POST;
unset($this->_bodyParams[$this->methodParam]);
return $this->_bodyParams;
}
$rawContentType = $this->getContentType();
if (($pos = strpos((string)$rawContentType, ';')) !== false) {
// e.g. text/html; charset=UTF-8
$contentType = substr($rawContentType, 0, $pos);
} else {
$contentType = $rawContentType;
}
if (isset($this->parsers[$contentType])) {
$parser = Yii::createObject($this->parsers[$contentType]);
if (!($parser instanceof RequestParserInterface)) {
throw new InvalidConfigException("The '$contentType' request parser is invalid. It must implement the yii\\web\\RequestParserInterface.");
}
$this->_bodyParams = $parser->parse($this->getRawBody(), $rawContentType);
} elseif (isset($this->parsers['*'])) {
$parser = Yii::createObject($this->parsers['*']);
if (!($parser instanceof RequestParserInterface)) {
throw new InvalidConfigException('The fallback request parser is invalid. It must implement the yii\\web\\RequestParserInterface.');
}
$this->_bodyParams = $parser->parse($this->getRawBody(), $rawContentType);
} elseif ($this->getMethod() === 'POST') {
// PHP has already parsed the body so we have all params in $_POST
$this->_bodyParams = $_POST;
} else {
$this->_bodyParams = [];
mb_parse_str($this->getRawBody(), $this->_bodyParams);
}
}
return $this->_bodyParams;
}
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. Empty string is returned if this information is not available. |
---|
public function getContentType()
{
if (isset($_SERVER['CONTENT_TYPE'])) {
return $_SERVER['CONTENT_TYPE'];
}
//fix bug https://bugs.php.net/bug.php?id=66606
return $this->headers->get('Content-Type') ?: '';
}
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. |
---|
public function getCookies()
{
if ($this->_cookies === null) {
$this->_cookies = new CookieCollection($this->loadCookies(), [
'readOnly' => true,
]);
}
return $this->_cookies;
}
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. |
---|
public function getCsrfToken($regenerate = false)
{
if ($this->_csrfToken === null || $regenerate) {
$token = $this->loadCsrfToken();
if ($regenerate || empty($token)) {
$token = $this->generateCsrfToken();
}
$this->_csrfToken = Yii::$app->security->maskToken($token);
}
return $this->_csrfToken;
}
public string|null getCsrfTokenFromHeader ( ) | ||
return | string|null |
The CSRF token sent via CSRF_HEADER by browser. Null is returned if no such header is sent. |
---|
public function getCsrfTokenFromHeader()
{
return $this->headers->get(static::CSRF_HEADER);
}
Gets the Etags.
public array getETags ( ) | ||
return | array |
The entity tags |
---|
public function getETags()
{
if ($this->headers->has('If-None-Match')) {
return preg_split('/[\s,]+/', str_replace('-gzip', '', $this->headers->get('If-None-Match')), -1, PREG_SPLIT_NO_EMPTY);
}
return [];
}
Returns the header collection.
The header collection contains incoming HTTP headers.
public yii\web\HeaderCollection getHeaders ( ) | ||
return | yii\web\HeaderCollection |
The header collection |
---|
public function getHeaders()
{
if ($this->_headers === null) {
$this->_headers = new HeaderCollection();
if (function_exists('getallheaders')) {
$headers = getallheaders();
foreach ($headers as $name => $value) {
$this->_headers->add($name, $value);
}
} elseif (function_exists('http_get_request_headers')) {
$headers = http_get_request_headers();
foreach ($headers as $name => $value) {
$this->_headers->add($name, $value);
}
} else {
// ['prefix' => length]
$headerPrefixes = ['HTTP_' => 5, 'REDIRECT_HTTP_' => 14];
foreach ($_SERVER as $name => $value) {
foreach ($headerPrefixes as $prefix => $length) {
if (strncmp($name, $prefix, $length) === 0) {
$name = str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, $length)))));
$this->_headers->add($name, $value);
continue 2;
}
}
}
}
$this->filterHeaders($this->_headers);
}
return $this->_headers;
}
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. |
---|
public function getHostInfo()
{
if ($this->_hostInfo === null) {
$secure = $this->getIsSecureConnection();
$http = $secure ? 'https' : 'http';
if ($this->getSecureForwardedHeaderTrustedPart('host') !== null) {
$this->_hostInfo = $http . '://' . $this->getSecureForwardedHeaderTrustedPart('host');
} elseif ($this->headers->has('X-Forwarded-Host')) {
$this->_hostInfo = $http . '://' . trim(explode(',', $this->headers->get('X-Forwarded-Host'))[0]);
} elseif ($this->headers->has('X-Original-Host')) {
$this->_hostInfo = $http . '://' . trim(explode(',', $this->headers->get('X-Original-Host'))[0]);
} elseif ($this->headers->has('Host')) {
$this->_hostInfo = $http . '://' . $this->headers->get('Host');
} elseif (isset($_SERVER['SERVER_NAME'])) {
$this->_hostInfo = $http . '://' . $_SERVER['SERVER_NAME'];
$port = $secure ? $this->getSecurePort() : $this->getPort();
if (($port !== 80 && !$secure) || ($port !== 443 && $secure)) {
$this->_hostInfo .= ':' . $port;
}
}
}
return $this->_hostInfo;
}
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. |
---|
public function getHostName()
{
if ($this->_hostName === null) {
$this->_hostName = parse_url((string)$this->getHostInfo(), PHP_URL_HOST);
}
return $this->_hostName;
}
Creates instance of yii\validators\IpValidator.
You can override this method to adjust validator or implement different matching strategy.
protected yii\validators\IpValidator getIpValidator ( ) |
protected function getIpValidator()
{
return new IpValidator();
}
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. |
---|
public function getIsAjax()
{
return $this->headers->get('X-Requested-With') === 'XMLHttpRequest';
}
Defined in: yii\base\Request::getIsConsoleRequest()
Returns a value indicating whether the current request is made via command line.
public boolean getIsConsoleRequest ( ) | ||
return | boolean |
The value indicating whether the current request is made via console |
---|
public function getIsConsoleRequest()
{
return $this->_isConsoleRequest !== null ? $this->_isConsoleRequest : PHP_SAPI === 'cli';
}
Returns whether this is a DELETE request.
public boolean getIsDelete ( ) | ||
return | boolean |
Whether this is a DELETE request. |
---|
public function getIsDelete()
{
return $this->getMethod() === 'DELETE';
}
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. |
---|
public function getIsFlash()
{
$userAgent = $this->headers->get('User-Agent', '');
return stripos($userAgent, 'Shockwave') !== false
|| stripos($userAgent, 'Flash') !== false;
}
Returns whether this is a GET request.
public boolean getIsGet ( ) | ||
return | boolean |
Whether this is a GET request. |
---|
public function getIsGet()
{
return $this->getMethod() === 'GET';
}
Returns whether this is a HEAD request.
public boolean getIsHead ( ) | ||
return | boolean |
Whether this is a HEAD request. |
---|
public function getIsHead()
{
return $this->getMethod() === 'HEAD';
}
Returns whether this is an OPTIONS request.
public boolean getIsOptions ( ) | ||
return | boolean |
Whether this is a OPTIONS request. |
---|
public function getIsOptions()
{
return $this->getMethod() === 'OPTIONS';
}
Returns whether this is a PATCH request.
public boolean getIsPatch ( ) | ||
return | boolean |
Whether this is a PATCH request. |
---|
public function getIsPatch()
{
return $this->getMethod() === 'PATCH';
}
Returns whether this is a PJAX request.
public boolean getIsPjax ( ) | ||
return | boolean |
Whether this is a PJAX request |
---|
public function getIsPjax()
{
return $this->getIsAjax() && $this->headers->has('X-Pjax');
}
Returns whether this is a POST request.
public boolean getIsPost ( ) | ||
return | boolean |
Whether this is a POST request. |
---|
public function getIsPost()
{
return $this->getMethod() === 'POST';
}
Returns whether this is a PUT request.
public boolean getIsPut ( ) | ||
return | boolean |
Whether this is a PUT request. |
---|
public function getIsPut()
{
return $this->getMethod() === 'PUT';
}
Return if the request is sent via secure channel (https).
public boolean getIsSecureConnection ( ) | ||
return | boolean |
If the request is sent via secure channel (https) |
---|
public function getIsSecureConnection()
{
if (isset($_SERVER['HTTPS']) && (strcasecmp($_SERVER['HTTPS'], 'on') === 0 || $_SERVER['HTTPS'] == 1)) {
return true;
}
if (($proto = $this->getSecureForwardedHeaderTrustedPart('proto')) !== null) {
return strcasecmp($proto, 'https') === 0;
}
foreach ($this->secureProtocolHeaders as $header => $values) {
if (($headerValue = $this->headers->get($header, null)) !== null) {
foreach ($values as $value) {
if (strcasecmp($headerValue, $value) === 0) {
return true;
}
}
}
}
return false;
}
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. |
---|
public function getMethod()
{
if (
isset($_POST[$this->methodParam])
// Never allow to downgrade request from WRITE methods (POST, PATCH, DELETE, etc)
// to read methods (GET, HEAD, OPTIONS) for security reasons.
&& !in_array(strtoupper($_POST[$this->methodParam]), ['GET', 'HEAD', 'OPTIONS'], true)
) {
return strtoupper($_POST[$this->methodParam]);
}
if ($this->headers->has('X-Http-Method-Override')) {
return strtoupper($this->headers->get('X-Http-Method-Override'));
}
if (isset($_SERVER['REQUEST_METHOD'])) {
return strtoupper($_SERVER['REQUEST_METHOD']);
}
return 'GET';
}
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, |
---|
public function getOrigin()
{
return $this->getHeaders()->get('origin');
}
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 |
public function getPathInfo()
{
if ($this->_pathInfo === null) {
$this->_pathInfo = $this->resolvePathInfo();
}
return $this->_pathInfo;
}
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. |
---|
public function getPort()
{
if ($this->_port === null) {
$serverPort = $this->getServerPort();
$this->_port = !$this->getIsSecureConnection() && $serverPort !== null ? $serverPort : 80;
}
return $this->_port;
}
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. |
---|
public function getPreferredLanguage(array $languages = [])
{
if (empty($languages)) {
return Yii::$app->language;
}
foreach ($this->getAcceptableLanguages() as $acceptableLanguage) {
$acceptableLanguage = str_replace('_', '-', strtolower($acceptableLanguage));
foreach ($languages as $language) {
$normalizedLanguage = str_replace('_', '-', strtolower($language));
if (
$normalizedLanguage === $acceptableLanguage // en-us==en-us
|| strpos($acceptableLanguage, $normalizedLanguage . '-') === 0 // en==en-us
|| strpos($normalizedLanguage, $acceptableLanguage . '-') === 0 // en-us==en
) {
return $language;
}
}
}
return reset($languages);
}
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 |
---|
public function getQueryParam($name, $defaultValue = null)
{
$params = $this->getQueryParams();
return isset($params[$name]) ? $params[$name] : $defaultValue;
}
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. |
---|
public function getQueryParams()
{
if ($this->_queryParams === null) {
return $_GET;
}
return $this->_queryParams;
}
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 |
---|
public function getQueryString()
{
return isset($_SERVER['QUERY_STRING']) ? $_SERVER['QUERY_STRING'] : '';
}
Returns the raw HTTP request body.
public string getRawBody ( ) | ||
return | string |
The request body |
---|
public function getRawBody()
{
if ($this->_rawBody === null) {
$this->_rawBody = file_get_contents('php://input');
}
return $this->_rawBody;
}
Returns the URL referrer.
public string|null getReferrer ( ) | ||
return | string|null |
URL referrer, null if not available |
---|
public function getReferrer()
{
return $this->headers->get('Referer');
}
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, |
---|
public function getRemoteHost()
{
return isset($_SERVER['REMOTE_HOST']) ? $_SERVER['REMOTE_HOST'] : null;
}
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, |
---|
public function getRemoteIP()
{
return isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : null;
}
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 |
public function getScriptFile()
{
if (isset($this->_scriptFile)) {
return $this->_scriptFile;
}
if (isset($_SERVER['SCRIPT_FILENAME'])) {
return $_SERVER['SCRIPT_FILENAME'];
}
throw new InvalidConfigException('Unable to determine the entry script file path.');
}
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 |
public function getScriptUrl()
{
if ($this->_scriptUrl === null) {
$scriptFile = $this->getScriptFile();
$scriptName = basename($scriptFile);
if (isset($_SERVER['SCRIPT_NAME']) && basename($_SERVER['SCRIPT_NAME']) === $scriptName) {
$this->_scriptUrl = $_SERVER['SCRIPT_NAME'];
} elseif (isset($_SERVER['PHP_SELF']) && basename($_SERVER['PHP_SELF']) === $scriptName) {
$this->_scriptUrl = $_SERVER['PHP_SELF'];
} elseif (isset($_SERVER['ORIG_SCRIPT_NAME']) && basename($_SERVER['ORIG_SCRIPT_NAME']) === $scriptName) {
$this->_scriptUrl = $_SERVER['ORIG_SCRIPT_NAME'];
} elseif (isset($_SERVER['PHP_SELF']) && ($pos = strpos($_SERVER['PHP_SELF'], '/' . $scriptName)) !== false) {
$this->_scriptUrl = substr($_SERVER['SCRIPT_NAME'], 0, $pos) . '/' . $scriptName;
} elseif (!empty($_SERVER['DOCUMENT_ROOT']) && strpos($scriptFile, $_SERVER['DOCUMENT_ROOT']) === 0) {
$this->_scriptUrl = str_replace([$_SERVER['DOCUMENT_ROOT'], '\\'], ['', '/'], $scriptFile);
} else {
throw new InvalidConfigException('Unable to determine the entry script URL.');
}
}
return $this->_scriptUrl;
}
Returns decoded forwarded header
protected array getSecureForwardedHeaderParts ( ) |
protected function getSecureForwardedHeaderParts()
{
if ($this->_secureForwardedHeaderParts !== null) {
return $this->_secureForwardedHeaderParts;
}
if (count(preg_grep('/^forwarded$/i', $this->secureHeaders)) === 0) {
return $this->_secureForwardedHeaderParts = [];
}
/*
* First header is always correct, because proxy CAN add headers
* after last one is found.
* Keep in mind that it is NOT enforced, therefore we cannot be
* sure, that this is really a first one.
*
* FPM keeps last header sent which is a bug. You need to merge
* headers together on your web server before letting FPM handle it
* @see https://bugs.php.net/bug.php?id=78844
*/
$forwarded = $this->headers->get('Forwarded', '');
if ($forwarded === '') {
return $this->_secureForwardedHeaderParts = [];
}
preg_match_all('/(?:[^",]++|"[^"]++")+/', $forwarded, $forwardedElements);
foreach ($forwardedElements[0] as $forwardedPairs) {
preg_match_all('/(?P<key>\w+)\s*=\s*(?:(?P<value>[^",;]*[^",;\s])|"(?P<value2>[^"]+)")/', $forwardedPairs, $matches, PREG_SET_ORDER);
$this->_secureForwardedHeaderParts[] = array_reduce($matches, function ($carry, $item) {
$value = $item['value'];
if (isset($item['value2']) && $item['value2'] !== '') {
$value = $item['value2'];
}
$carry[strtolower($item['key'])] = $value;
return $carry;
}, []);
}
return $this->_secureForwardedHeaderParts;
}
Gets first Forwarded
header value for token
protected string|null getSecureForwardedHeaderTrustedPart ( $token ) | ||
$token | string |
Header token |
protected function getSecureForwardedHeaderTrustedPart($token)
{
$token = strtolower($token);
if ($parts = $this->getSecureForwardedHeaderTrustedParts()) {
$lastElement = array_pop($parts);
if ($lastElement && isset($lastElement[$token])) {
return $lastElement[$token];
}
}
return null;
}
Gets only trusted Forwarded
header parts
protected array getSecureForwardedHeaderTrustedParts ( ) |
protected function getSecureForwardedHeaderTrustedParts()
{
if ($this->_secureForwardedHeaderTrustedParts !== null) {
return $this->_secureForwardedHeaderTrustedParts;
}
$validator = $this->getIpValidator();
$trustedHosts = [];
foreach ($this->trustedHosts as $trustedCidr => $trustedCidrOrHeaders) {
if (!is_array($trustedCidrOrHeaders)) {
$trustedCidr = $trustedCidrOrHeaders;
}
$trustedHosts[] = $trustedCidr;
}
$validator->setRanges($trustedHosts);
$this->_secureForwardedHeaderTrustedParts = array_filter(
$this->getSecureForwardedHeaderParts(),
function ($headerPart) use ($validator) {
return isset($headerPart['for']) ? !$validator->validate($headerPart['for']) : true;
}
);
return $this->_secureForwardedHeaderTrustedParts;
}
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. |
---|
public function getSecurePort()
{
if ($this->_securePort === null) {
$serverPort = $this->getServerPort();
$this->_securePort = $this->getIsSecureConnection() && $serverPort !== null ? $serverPort : 443;
}
return $this->_securePort;
}
Returns the server name.
public string|null getServerName ( ) | ||
return | string|null |
Server name, null if not available |
---|
public function getServerName()
{
return isset($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'] : 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.
See also $portHeaders.
public integer|null getServerPort ( ) | ||
return | integer|null |
Server port number, null if not available |
---|
public function getServerPort()
{
foreach ($this->portHeaders as $portHeader) {
if ($this->headers->has($portHeader)) {
$port = $this->headers->get($portHeader);
if ($port !== null) {
return $port;
}
}
}
return isset($_SERVER['SERVER_PORT']) ? (int) $_SERVER['SERVER_PORT'] : null;
}
Trusted headers according to the $trustedHosts.
protected array getTrustedHeaders ( ) |
protected function getTrustedHeaders()
{
// do not trust any of the [[secureHeaders]] by default
$trustedHeaders = [];
// check if the client is a trusted host
if (!empty($this->trustedHosts)) {
$validator = $this->getIpValidator();
$ip = $this->getRemoteIP();
foreach ($this->trustedHosts as $cidr => $headers) {
if (!is_array($headers)) {
$cidr = $headers;
$headers = $this->secureHeaders;
}
$validator->setRanges($cidr);
if ($validator->validate($ip)) {
$trustedHeaders = $headers;
break;
}
}
}
return $trustedHeaders;
}
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 |
public function getUrl()
{
if ($this->_url === null) {
$this->_url = $this->resolveRequestUri();
}
return $this->_url;
}
Returns the user agent.
public string|null getUserAgent ( ) | ||
return | string|null |
User agent, null if not available |
---|
public function getUserAgent()
{
return $this->headers->get('User-Agent');
}
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 |
---|
public function getUserHost()
{
$userIp = $this->getUserIpFromIpHeaders();
if ($userIp === null) {
return $this->getRemoteHost();
}
return gethostbyaddr($userIp);
}
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 |
---|
public function getUserIP()
{
if ($this->_ip === null) {
$this->_ip = $this->getUserIpFromIpHeaders();
if ($this->_ip === null) {
$this->_ip = $this->getRemoteIP();
}
}
return $this->_ip;
}
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. |
---|
protected function getUserIpFromIpHeader($ips)
{
$ips = trim($ips);
if ($ips === '') {
return null;
}
$ips = preg_split('/\s*,\s*/', $ips, -1, PREG_SPLIT_NO_EMPTY);
krsort($ips);
$validator = $this->getIpValidator();
$resultIp = null;
foreach ($ips as $ip) {
$validator->setRanges('any');
if (!$validator->validate($ip) /* checking IP format */) {
break;
}
$resultIp = $ip;
$isTrusted = false;
foreach ($this->trustedHosts as $trustedCidr => $trustedCidrOrHeaders) {
if (!is_array($trustedCidrOrHeaders)) {
$trustedCidr = $trustedCidrOrHeaders;
}
$validator->setRanges($trustedCidr);
if ($validator->validate($ip) /* checking trusted range */) {
$isTrusted = true;
break;
}
}
if (!$isTrusted) {
break;
}
}
return $resultIp;
}
Returns the user IP address from $ipHeaders.
See also $ipHeaders.
protected string|null getUserIpFromIpHeaders ( ) | ||
return | string|null |
User IP address, null if not available |
---|
protected function getUserIpFromIpHeaders()
{
$ip = $this->getSecureForwardedHeaderTrustedPart('for');
if (
$ip !== null && preg_match(
'/^\[?(?P<ip>(?:(?:(?:[0-9a-f]{1,4}:){1,6}(?:[0-9a-f]{1,4})?(?:(?::[0-9a-f]{1,4}){1,6}))|(?:\d{1,3}\.){3}\d{1,3}))\]?(?::(?P<port>\d+))?$/',
$ip,
$matches
)
) {
$ip = $this->getUserIpFromIpHeader($matches['ip']);
if ($ip !== null) {
return $ip;
}
}
foreach ($this->ipHeaders as $ipHeader) {
if ($this->headers->has($ipHeader)) {
$ip = $this->getUserIpFromIpHeader($this->headers->get($ipHeader));
if ($ip !== null) {
return $ip;
}
}
}
return null;
}
Defined in: yii\base\Component::hasEventHandlers()
Returns a value indicating whether there is any handler attached to the named event.
public boolean hasEventHandlers ( $name ) | ||
$name | string |
The event name |
return | boolean |
Whether there is any handler attached to the event. |
---|
public function hasEventHandlers($name)
{
$this->ensureBehaviors();
if (!empty($this->_events[$name])) {
return true;
}
foreach ($this->_eventWildcards as $wildcard => $handlers) {
if (!empty($handlers) && StringHelper::matchWildcard($wildcard, $name)) {
return true;
}
}
return Event::hasHandlers($this, $name);
}
Defined in: yii\base\Component::hasMethod()
Returns a value indicating whether a method is defined.
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).
public boolean hasMethod ( $name, $checkBehaviors = true ) | ||
$name | string |
The property name |
$checkBehaviors | boolean |
Whether to treat behaviors' methods as methods of this component |
return | boolean |
Whether the method is defined |
---|
public function hasMethod($name, $checkBehaviors = true)
{
if (method_exists($this, $name)) {
return true;
} elseif ($checkBehaviors) {
$this->ensureBehaviors();
foreach ($this->_behaviors as $behavior) {
if ($behavior->hasMethod($name)) {
return true;
}
}
}
return false;
}
Defined in: yii\base\Component::hasProperty()
Returns a value indicating whether a property is defined for this component.
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).
See also:
public boolean hasProperty ( $name, $checkVars = true, $checkBehaviors = true ) | ||
$name | string |
The property name |
$checkVars | boolean |
Whether to treat member variables as properties |
$checkBehaviors | boolean |
Whether to treat behaviors' properties as properties of this component |
return | boolean |
Whether the property is defined |
---|
public function hasProperty($name, $checkVars = true, $checkBehaviors = true)
{
return $this->canGetProperty($name, $checkVars, $checkBehaviors) || $this->canSetProperty($name, false, $checkBehaviors);
}
Defined in: yii\base\BaseObject::init()
Initializes the object.
This method is invoked at the end of the constructor after the object is initialized with the given configuration.
public void init ( ) |
public function init()
{
}
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 |
protected function loadCookies()
{
$cookies = [];
if ($this->enableCookieValidation) {
if ($this->cookieValidationKey == '') {
throw new InvalidConfigException(get_class($this) . '::cookieValidationKey must be configured with a secret key.');
}
foreach ($_COOKIE as $name => $value) {
if (!is_string($value)) {
continue;
}
$data = Yii::$app->getSecurity()->validateData($value, $this->cookieValidationKey);
if ($data === false) {
continue;
}
if (defined('PHP_VERSION_ID') && PHP_VERSION_ID >= 70000) {
$data = @unserialize($data, ['allowed_classes' => false]);
} else {
$data = @unserialize($data);
}
if (is_array($data) && isset($data[0], $data[1]) && $data[0] === $name) {
$cookies[$name] = Yii::createObject([
'class' => 'yii\web\Cookie',
'name' => $name,
'value' => $data[1],
'expire' => null,
]);
}
}
} else {
foreach ($_COOKIE as $name => $value) {
$cookies[$name] = Yii::createObject([
'class' => 'yii\web\Cookie',
'name' => $name,
'value' => $value,
'expire' => null,
]);
}
}
return $cookies;
}
Loads the CSRF token from cookie or session.
protected string|null loadCsrfToken ( ) | ||
return | string|null |
The CSRF token loaded from cookie or session. Null is returned if the cookie or session does not have CSRF token. |
---|
protected function loadCsrfToken()
{
if ($this->enableCsrfCookie) {
return $this->getCookies()->getValue($this->csrfParam);
}
return Yii::$app->getSession()->get($this->csrfParam);
}
Defined in: yii\base\Component::off()
Detaches an existing event handler from this component.
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.
See also on().
public boolean off ( $name, $handler = null ) | ||
$name | string |
Event name |
$handler | callable|null |
The event handler to be removed. If it is null, all handlers attached to the named event will be removed. |
return | boolean |
If a handler is found and detached |
---|
public function off($name, $handler = null)
{
$this->ensureBehaviors();
if (empty($this->_events[$name]) && empty($this->_eventWildcards[$name])) {
return false;
}
if ($handler === null) {
unset($this->_events[$name], $this->_eventWildcards[$name]);
return true;
}
$removed = false;
// plain event names
if (isset($this->_events[$name])) {
foreach ($this->_events[$name] as $i => $event) {
if ($event[0] === $handler) {
unset($this->_events[$name][$i]);
$removed = true;
}
}
if ($removed) {
$this->_events[$name] = array_values($this->_events[$name]);
return true;
}
}
// wildcard event names
if (isset($this->_eventWildcards[$name])) {
foreach ($this->_eventWildcards[$name] as $i => $event) {
if ($event[0] === $handler) {
unset($this->_eventWildcards[$name][$i]);
$removed = true;
}
}
if ($removed) {
$this->_eventWildcards[$name] = array_values($this->_eventWildcards[$name]);
// remove empty wildcards to save future redundant regex checks:
if (empty($this->_eventWildcards[$name])) {
unset($this->_eventWildcards[$name]);
}
}
}
return $removed;
}
Defined in: yii\base\Component::on()
Attaches an event handler to an event.
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 yii\base\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.');
});
See also off().
public void on ( $name, $handler, $data = null, $append = true ) | ||
$name | string |
The event name |
$handler | callable |
The event handler |
$data | mixed |
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 yii\base\Event::$data. |
$append | boolean |
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. |
public function on($name, $handler, $data = null, $append = true)
{
$this->ensureBehaviors();
if (strpos($name, '*') !== false) {
if ($append || empty($this->_eventWildcards[$name])) {
$this->_eventWildcards[$name][] = [$handler, $data];
} else {
array_unshift($this->_eventWildcards[$name], [$handler, $data]);
}
return;
}
if ($append || empty($this->_events[$name])) {
$this->_events[$name][] = [$handler, $data];
} else {
array_unshift($this->_events[$name], [$handler, $data]);
}
}
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. |
---|
public function parseAcceptHeader($header)
{
$accepts = [];
foreach (explode(',', $header) as $i => $part) {
$params = preg_split('/\s*;\s*/', trim($part), -1, PREG_SPLIT_NO_EMPTY);
if (empty($params)) {
continue;
}
$values = [
'q' => [$i, array_shift($params), 1],
];
foreach ($params as $param) {
if (strpos($param, '=') !== false) {
list($key, $value) = explode('=', $param, 2);
if ($key === 'q') {
$values['q'][2] = (float) $value;
} else {
$values[$key] = $value;
}
} else {
$values[] = $param;
}
}
$accepts[] = $values;
}
usort($accepts, function ($a, $b) {
$a = $a['q']; // index, name, q
$b = $b['q'];
if ($a[2] > $b[2]) {
return -1;
}
if ($a[2] < $b[2]) {
return 1;
}
if ($a[1] === $b[1]) {
return $a[0] > $b[0] ? 1 : -1;
}
if ($a[1] === '*/*') {
return 1;
}
if ($b[1] === '*/*') {
return -1;
}
$wa = $a[1][strlen($a[1]) - 1] === '*';
$wb = $b[1][strlen($b[1]) - 1] === '*';
if ($wa xor $wb) {
return $wa ? 1 : -1;
}
return $a[0] > $b[0] ? 1 : -1;
});
$result = [];
foreach ($accepts as $accept) {
$name = $accept['q'][1];
$accept['q'] = $accept['q'][2];
$result[$name] = $accept;
}
return $result;
}
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. |
public function post($name = null, $defaultValue = null)
{
if ($name === null) {
return $this->getBodyParams();
}
return $this->getBodyParam($name, $defaultValue);
}
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. |
public function resolve()
{
$result = Yii::$app->getUrlManager()->parseRequest($this);
if ($result !== false) {
list($route, $params) = $result;
if ($this->_queryParams === null) {
$_GET = $params + $_GET; // preserve numeric keys
} else {
$this->_queryParams = $params + $this->_queryParams;
}
return [$route, $this->getQueryParams()];
}
throw new NotFoundHttpException(Yii::t('yii', 'Page not found.'));
}
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 |
protected function resolvePathInfo()
{
$pathInfo = $this->getUrl();
if (($pos = strpos($pathInfo, '?')) !== false) {
$pathInfo = substr($pathInfo, 0, $pos);
}
$pathInfo = urldecode($pathInfo);
// try to encode in UTF8 if not so
// https://www.w3.org/International/questions/qa-forms-utf-8.en.html
if (
!preg_match('%^(?:
[\x09\x0A\x0D\x20-\x7E] # ASCII
| [\xC2-\xDF][\x80-\xBF] # non-overlong 2-byte
| \xE0[\xA0-\xBF][\x80-\xBF] # excluding overlongs
| [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} # straight 3-byte
| \xED[\x80-\x9F][\x80-\xBF] # excluding surrogates
| \xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3
| [\xF1-\xF3][\x80-\xBF]{3} # planes 4-15
| \xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16
)*$%xs', $pathInfo)
) {
$pathInfo = $this->utf8Encode($pathInfo);
}
$scriptUrl = $this->getScriptUrl();
$baseUrl = $this->getBaseUrl();
if (strpos($pathInfo, $scriptUrl) === 0) {
$pathInfo = substr($pathInfo, strlen($scriptUrl));
} elseif ($baseUrl === '' || strpos($pathInfo, $baseUrl) === 0) {
$pathInfo = substr($pathInfo, strlen($baseUrl));
} elseif (isset($_SERVER['PHP_SELF']) && strpos($_SERVER['PHP_SELF'], $scriptUrl) === 0) {
$pathInfo = substr($_SERVER['PHP_SELF'], strlen($scriptUrl));
} else {
throw new InvalidConfigException('Unable to determine the path info of the current request.');
}
if (strncmp($pathInfo, '/', 1) === 0) {
$pathInfo = substr($pathInfo, 1);
}
return (string) $pathInfo;
}
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 |
protected function resolveRequestUri()
{
if ($this->headers->has('X-Rewrite-Url')) { // IIS
$requestUri = $this->headers->get('X-Rewrite-Url');
} elseif (isset($_SERVER['REQUEST_URI'])) {
$requestUri = $_SERVER['REQUEST_URI'];
if ($requestUri !== '' && $requestUri[0] !== '/') {
$requestUri = preg_replace('/^(http|https):\/\/[^\/]+/i', '', $requestUri);
}
} elseif (isset($_SERVER['ORIG_PATH_INFO'])) { // IIS 5.0 CGI
$requestUri = $_SERVER['ORIG_PATH_INFO'];
if (!empty($_SERVER['QUERY_STRING'])) {
$requestUri .= '?' . $_SERVER['QUERY_STRING'];
}
} else {
throw new InvalidConfigException('Unable to determine the request URI.');
}
return $requestUri;
}
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. |
public function setAcceptableContentTypes($value)
{
$this->_contentTypes = $value;
}
public void setAcceptableLanguages ( $value ) | ||
$value | array |
The languages that are acceptable by the end user. They should be ordered by the preference level. |
public function setAcceptableLanguages($value)
{
$this->_languages = $value;
}
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 |
public function setBaseUrl($value)
{
$this->_baseUrl = $value;
}
Sets the request body parameters.
See also getBodyParams().
public void setBodyParams ( $values ) | ||
$values | array|object |
The request body parameters (name-value pairs) |
public function setBodyParams($values)
{
$this->_bodyParams = $values;
}
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. |
public function setHostInfo($value)
{
$this->_hostName = null;
$this->_hostInfo = $value === null ? null : rtrim($value, '/');
}
Defined in: yii\base\Request::setIsConsoleRequest()
Sets the value indicating whether the current request is made via command line.
public void setIsConsoleRequest ( $value ) | ||
$value | boolean |
The value indicating whether the current request is made via command line |
public function setIsConsoleRequest($value)
{
$this->_isConsoleRequest = $value;
}
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 |
public function setPathInfo($value)
{
$this->_pathInfo = $value === null ? null : ltrim($value, '/');
}
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. |
public function setPort($value)
{
if ($value != $this->_port) {
$this->_port = (int) $value;
$this->_hostInfo = null;
}
}
public void setQueryParams ( $values ) | ||
$values | array |
The request query parameters (name-value pairs) |
public function setQueryParams($values)
{
$this->_queryParams = $values;
}
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 |
public function setRawBody($rawBody)
{
$this->_rawBody = $rawBody;
}
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. |
public function setScriptFile($value)
{
$this->_scriptFile = $value;
}
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. |
public function setScriptUrl($value)
{
$this->_scriptUrl = $value === null ? null : '/' . trim($value, '/');
}
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. |
public function setSecurePort($value)
{
if ($value != $this->_securePort) {
$this->_securePort = (int) $value;
$this->_hostInfo = null;
}
}
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 |
public function setUrl($value)
{
$this->_url = $value;
}
Defined in: yii\base\Component::trigger()
Triggers an event.
This method represents the happening of an event. It invokes all attached handlers for the event including class-level handlers.
public void trigger ( $name, yii\base\Event $event = null ) | ||
$name | string |
The event name |
$event | yii\base\Event|null |
The event instance. If not set, a default yii\base\Event object will be created. |
public function trigger($name, Event $event = null)
{
$this->ensureBehaviors();
$eventHandlers = [];
foreach ($this->_eventWildcards as $wildcard => $handlers) {
if (StringHelper::matchWildcard($wildcard, $name)) {
$eventHandlers[] = $handlers;
}
}
if (!empty($this->_events[$name])) {
$eventHandlers[] = $this->_events[$name];
}
if (!empty($eventHandlers)) {
$eventHandlers = call_user_func_array('array_merge', $eventHandlers);
if ($event === null) {
$event = new Event();
}
if ($event->sender === null) {
$event->sender = $this;
}
$event->handled = false;
$event->name = $name;
foreach ($eventHandlers as $handler) {
$event->data = $handler[1];
call_user_func($handler[0], $event);
// stop further handling if the event is handled
if ($event->handled) {
return;
}
}
}
// invoke class-level attached handlers
Event::trigger($this, $name, $event);
}
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|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 | boolean |
Whether CSRF token is valid. If $enableCsrfValidation is false, this method will return true. |
---|
public function validateCsrfToken($clientSuppliedToken = null)
{
$method = $this->getMethod();
// only validate CSRF token on non-"safe" methods https://tools.ietf.org/html/rfc2616#section-9.1.1
if (!$this->enableCsrfValidation || in_array($method, ['GET', 'HEAD', 'OPTIONS'], true)) {
return true;
}
$trueToken = $this->getCsrfToken();
if ($clientSuppliedToken !== null) {
return $this->validateCsrfTokenInternal($clientSuppliedToken, $trueToken);
}
return $this->validateCsrfTokenInternal($this->getBodyParam($this->csrfParam), $trueToken)
|| $this->validateCsrfTokenInternal($this->getCsrfTokenFromHeader(), $trueToken);
}
Signup or Login in order to comment.