Request

Type
Class
Namespace
craft\web
Inherits
craft\web\Request » yii\web\Request » yii\base\Request » yii\base\Component » yii\base\BaseObject
Implements
yii\base\Configurable
Uses traits
craft\base\RequestTrait
Since
3.0

View source

Public Properties

PropertyDescription
_tokenstring, false
absoluteUrlstring – The currently requested absolute URL.
acceptableContentTypesarray – The content types ordered by the quality score.
acceptableLanguagesarray – The languages ordered by the preference level.
acceptsJsonboolean
actionSegmentsarray, null – The action path segments, or null if this isn’t an action request.
authCredentialsarray – 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
authPasswordstring, null – The password sent via HTTP authentication, null if the password is not given
authUserstring, null – The username sent via HTTP authentication, null if the username is not given
baseUrlstring – The relative URL for the application
behaviorsyii\base\Behavior – List of behaviors attached to this component
bodyParamsarray – The request parameters given in the request body.
clientOsstring – The OS the client is running.
contentTypestring – Request content-type.
cookieValidationKeystring – A secret key used for cookie validation.
cookiesyii\web\CookieCollection – The cookie collection.
csrfCookiearray – The configuration for creating the CSRF \craft\web\Cookie.
csrfParamstring – The name of the token used to prevent CSRF.
csrfTokenstring – The token used to perform CSRF validation.
csrfTokenFromHeaderstring – The CSRF token sent via CSRF_HEADER by browser.
eTagsarray – The entity tags
enableCookieValidationboolean – Whether cookies should be validated to ensure they are not tampered.
enableCsrfCookieboolean – Whether to use cookie to persist CSRF token.
enableCsrfValidationboolean – Whether to enable CSRF (Cross-Site Request Forgery) validation.
fullPathstring
headersyii\web\HeaderCollection – The header collection
hostInfostring, null – Schema and hostname part (with port number if needed) of the request URL (e.g. `http://www.
hostNamestring, null – Hostname part of the request URL (e.g. `www.
ipHeadersstring[] – List of headers where proxies store the real client IP.
isActionRequestboolean – Whether the current request should be routed to a controller action.
isAjaxboolean – Whether this is an AJAX (XMLHttpRequest) request.
isConsoleRequestboolean – The value indicating whether the current request is made via console
isCpRequestboolean – Whether the current request should be routed to the Control Panel.
isDeleteboolean – Whether this is a DELETE request.
isFlashboolean – Whether this is an Adobe Flash or Adobe Flex request.
isGetboolean – Whether this is a GET request.
isHeadboolean – Whether this is a HEAD request.
isLivePreviewboolean – Whether this is a Live Preview request.
isLoginRequestboolean
isOptionsboolean – Whether this is a OPTIONS request.
isPatchboolean – Whether this is a PATCH request.
isPjaxboolean – Whether this is a PJAX request
isPostboolean – Whether this is a POST request.
isPreviewboolean
isPutboolean – Whether this is a PUT request.
isSecureConnectionboolean – If the request is sent via secure channel (https)
isSingleActionRequestboolean
isSiteRequestboolean – Whether the current request should be routed to the front-end site.
isWebAliasSetDynamicallyboolean
isWebrootAliasSetDynamicallyboolean
maxPageNum
methodstring – Request method, such as GET, POST, HEAD, PUT, PATCH, DELETE.
methodParamstring – The name of the POST parameter that is used to indicate if a request is a PUT, PATCH or DELETE request tunneled through POST.
originstring, null – URL origin of a CORS request, null if not available.
pageNuminteger – The requested page number.
parsersarray – The parsers for converting the raw HTTP request body into bodyParams.
pathInfostring – The requested path, or the path info.
portinteger – Port number for insecure requests.
preferredLanguagestring – The language that the application should use.
queryParamsarray – The request GET parameter values.
queryStringstring – Part of the request URL that is after the question mark
queryStringWithoutPathstring – The query string.
rawBodystring – The request body
referrerstring, null – URL referrer, null if not available
remoteHoststring, null – Remote host name, null if not available
remoteIPstring, null – Remote IP address, null if not available.
scriptFilestring – Entry script file path (processed w/ realpath())
scriptFilenamestring
scriptUrlstring – The relative URL of the entry script.
secureHeadersarray – Lists of headers that are, by default, subject to the trusted host configuration.
securePortinteger – Port number for secure requests.
secureProtocolHeadersarray – List of headers to check for determining whether the connection is made via HTTPS.
segmentsarray – The Craft path’s segments.
serverNamestring – Server name, null if not available
serverPortinteger, null – Server port number, null if not available
tokenstring, null – The token, or null if there isn’t one.
trustedHostsarray – The configuration for trusted security related headers.
urlstring – The currently requested relative URL.
userAgentstring, null – User agent, null if not available
userHoststring, null – User host name, null if not available
userIPstring, null – User IP address, null if not available

_token

Type
string, false

See also getToken()

View source

acceptsJson

Type
boolean
Access
Read-only

View source

actionSegments

Type
array, null
Access
Read-only

The action path segments, or null if this isn’t an action request.

View source

bodyParams

Type
array

The request parameters given in the request body.

View source

clientOs

Type
string
Access
Read-only

The OS the client is running.

View source

csrfToken

Type
string
Access
Read-only

The token used to perform CSRF validation.

View source

fullPath

Type
string
Access
Read-only

View source

ipHeaders

Type
string[]

List of headers where proxies store the real client IP. It's not advisable to put insecure headers here. The match of header names is case-insensitive.

View source

isActionRequest

Type
boolean
Access
Read-only

Whether the current request should be routed to a controller action.

View source

isCpRequest

Type
boolean
Access
Read-only

Whether the current request should be routed to the Control Panel.

View source

isLivePreview

Type
boolean

Whether this is a Live Preview request.

View source

isLoginRequest

Type
boolean
Access
Read-only

View source

isPreview

Type
boolean
Access
Read-only

View source

isSingleActionRequest

Type
boolean
Access
Read-only

View source

isSiteRequest

Type
boolean
Access
Read-only

Whether the current request should be routed to the front-end site.

View source

maxPageNum

Type

:

View source

pageNum

Type
integer
Access
Read-only

The requested page number.

View source

pathInfo

Type
string

The requested path, or the path info.

View source

queryParams

Type
array

The request GET parameter values.

View source

queryStringWithoutPath

Type
string
Access
Read-only

The query string.

View source

remoteIP

Type
string, null
Access
Read-only

Remote IP address, null if not available.

View source

segments

Type
array
Access
Read-only

The Craft path’s segments.

View source

token

Type
string, null
Access
Read-only

The token, or null if there isn’t one.

View source

userIP

Type
string, null
Access
Read-only

User IP address, null if not available

View source

Public Methods

MethodDescription
__call()Calls the named method which is not a class method.
__clone()This method is called after the object is created by cloning an existing one.
__construct()Constructor.
__get()Returns the value of an object property.
__isset()Checks if a property is set, i.e. defined and not null.
__set()Sets value of an object property.
__unset()Sets an object property to null.
accepts()Returns whether the request will accept a given content type3
attachBehavior()Attaches a behavior to this component.
attachBehaviors()Attaches a list of behaviors to the component.
behaviors()Returns a list of behaviors that this component should behave as.
canGetProperty()Returns a value indicating whether a property can be read.
canSetProperty()Returns a value indicating whether a property can be set.
className()Returns the fully qualified name of this class.
detachBehavior()Detaches a behavior from the component.
detachBehaviors()Detaches all behaviors from the component.
ensureBehaviors()Makes sure that the behaviors declared in behaviors() are attached to this component.
get()Returns GET parameter with a given name. If name isn't specified, returns an array of all GET parameters.
getAbsoluteUrl()Returns the currently requested absolute URL.
getAcceptableContentTypes()Returns the content types acceptable by the end user.
getAcceptableLanguages()Returns the languages acceptable by the end user.
getAcceptsJson()Returns whether the request will accept a JSON response.
getActionSegments()Returns the segments of the requested controller action path, if this is an action request.
getAuthCredentials()
getAuthPassword()
getAuthUser()
getBaseUrl()Returns the relative URL for the application.
getBehavior()Returns the named behavior object.
getBehaviors()Returns all behaviors attached to this component.
getBodyParam()Returns the named request body parameter value.
getBodyParams()Returns the request parameters given in the request body.
getClientOs()Returns whether the client is running "Windows", "Mac", "Linux" or "Other", based on the browser's UserAgent string.
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.
getCookies()Returns the cookie collection.
getCsrfToken()Returns the token used to perform CSRF validation.
getCsrfTokenFromHeader()
getETags()Gets the Etags.
getFullPath()Returns the full request path, whether that came from the path info or the path query parameter.
getHeaders()Returns the header collection.
getHostInfo()Returns the schema and host part of the current request URL.
getHostName()Returns the host part of the current request URL.
getIsActionRequest()Returns whether a specific controller action was requested.
getIsAjax()Returns whether this is an AJAX (XMLHttpRequest) request.
getIsConsoleRequest()Returns a value indicating whether the current request is made via command line.
getIsCpRequest()Returns whether the Control Panel was requested.
getIsDelete()Returns whether this is a DELETE request.
getIsFlash()Returns whether this is an Adobe Flash or Flex request.
getIsGet()Returns whether this is a GET request.
getIsHead()Returns whether this is a HEAD request.
getIsLivePreview()Returns whether this is a Live Preview request.
getIsLoginRequest()Returns whether this was a Login request.
getIsOptions()Returns whether this is an OPTIONS request.
getIsPatch()Returns whether this is a PATCH request.
getIsPjax()Returns whether this is a PJAX request.
getIsPost()Returns whether this is a POST request.
getIsPreview()Returns whether this is an element preview request.
getIsPut()Returns whether this is a PUT request.
getIsSecureConnection()Return if the request is sent via secure channel (https).
getIsSingleActionRequest()Returns whether the current request is solely an action request.
getIsSiteRequest()Returns whether the front end site was requested.
getMethod()Returns the method of the current request (e.g. GET, POST, HEAD, PUT, PATCH, DELETE).
getOrigin()Returns the URL origin of a CORS request.
getPageNum()Returns the requested page number.
getParam()Returns the named parameter value from either GET or the request body.
getPathInfo()Returns the requested path, sans CP trigger and pagination info.
getPort()Returns the port to use for insecure requests.
getPreferredLanguage()Returns the user-preferred language that should be used by this application.
getQueryParam()Returns the named GET parameter value.
getQueryParams()Returns the request parameters given in the queryString.
getQueryString()Returns part of the request URL that is after the question mark.
getQueryStringWithoutPath()Returns the request’s query string, without the path parameter.
getRawBody()Returns the raw HTTP request body.
getReferrer()Returns the URL referrer.
getRemoteHost()Returns the host name of the other end of this connection.
getRemoteIP()Returns the IP on the other end of this connection.
getRequiredBodyParam()Returns the named request body parameter value, or bails on the request with a 400 error if that parameter doesn’t exist.
getRequiredParam()Returns the named parameter value from either GET or the request body, or bails on the request with a 400 error if that parameter doesn’t exist anywhere.
getRequiredQueryParam()Returns the named GET parameter value, or bails on the request with a 400 error if that parameter doesn’t exist.
getScriptFile()Returns entry script file path.
getScriptFilename()Returns the requested script name being used to access Craft (e.g. “index.php”).
getScriptUrl()Returns the relative URL of the entry script.
getSecurePort()Returns the port to use for secure requests.
getSegment()Returns a specific segment from the Craft path.
getSegments()Returns the segments of the requested path.
getServerName()Returns the server name.
getServerPort()Returns the server port number.
getToken()Returns the token submitted with the request, if there is one.
getUrl()Returns the currently requested relative URL.
getUserAgent()Returns the user agent.
getUserHost()Returns the user host name.
getUserIP()Returns the user IP address.
getValidatedBodyParam()Validates and returns the named request body parameter value, or bails on the request with a 400 error if that parameter doesn’t pass validation.
hasEventHandlers()Returns a value indicating whether there is any handler attached to the named event.
hasMethod()Returns a value indicating whether a method is defined.
hasProperty()Returns a value indicating whether a property is defined.
init()Initializes the object.
isMobileBrowser()Returns whether the request is coming from a mobile browser.
off()Detaches an existing event handler from this component.
on()Attaches an event handler to an event.
parseAcceptHeader()Parses the given Accept (or Accept-Language) header.
post()Returns POST parameter with a given name. If name isn't specified, returns an array of all POST parameters.
regenCsrfToken()Regenerates a CSRF token.
setAcceptableContentTypes()Sets the acceptable content types.
setAcceptableLanguages()
setBaseUrl()Sets the relative URL for the application.
setBodyParams()Sets the request body parameters.
setHostInfo()Sets the schema and host part of the application URL.
setIsConsoleRequest()Sets the value indicating whether the current request is made via command line.
setIsLivePreview()Sets whether this is a Live Preview request.
setPathInfo()Sets the path info of the current request.
setPort()Sets the port to use for insecure requests.
setQueryParams()Sets the request queryString parameters.
setRawBody()Sets the raw HTTP request body, this method is mainly used by test scripts to simulate raw HTTP requests.
setScriptFile()Sets the entry script file path.
setScriptUrl()Sets the relative URL for the application entry script.
setSecurePort()Sets the port to use for secure requests.
setUrl()Sets the currently requested relative URL.
trigger()Triggers an event.
validateCsrfToken()Performs the CSRF validation.

accepts()

Returns whether the request will accept a given content type3

View source

Arguments

Returns

boolean

getAcceptsJson()

Returns whether the request will accept a JSON response.

View source

Returns

boolean

getActionSegments()

Returns the segments of the requested controller action path, if this is an action request.

View source

Returns

array, null – The action path segments, or null if this isn’t an action request.

getBodyParam()

Returns the named request body parameter value. If the parameter does not exist, the second argument passed to this method will be returned.

See also:

View source

Arguments

  • $name (string) – The parameter name.
  • $defaultValue (mixed) – The default parameter value if the parameter does not exist.

Returns

mixed – The parameter value

Example

getBodyParams()

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.

View source

Returns

array – The request parameters given in the request body.

Throws

getClientOs()

Returns whether the client is running "Windows", "Mac", "Linux" or "Other", based on the browser's UserAgent string.

View source

Returns

string – The OS the client is running.

Example

getCsrfToken()

Returns the token used to perform CSRF validation. This token is a masked version of \craft\web\rawCsrfToken to prevent BREACH attacks. This token may be passed along via a hidden field of an HTML form or an HTTP header value to support CSRF validation.

View source

Arguments

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

Returns

string – The token used to perform CSRF validation.

getFullPath()

Returns the full request path, whether that came from the path info or the path query parameter. Leading and trailing slashes will be removed.

View source

Returns

string

getIsActionRequest()

Returns whether a specific controller action was requested. There are several ways that this method could return true:

  • If the first segment in the Craft path matches the action trigger
  • If there is an 'action' param in either the POST data or query string
  • If the Craft path matches the Login path, the Logout path, or the Set Password path

View source

Returns

boolean – Whether the current request should be routed to a controller action.

getIsCpRequest()

Returns whether the Control Panel was requested. The result depends on whether the first segment in the URI matches the CP trigger.

View source

Returns

boolean – Whether the current request should be routed to the Control Panel.

getIsLivePreview()

DEPRECATED

Deprecated in 3.2

Returns whether this is a Live Preview request.

View source

Returns

boolean – Whether this is a Live Preview request.

Example

getIsLoginRequest()

Since
3.2.0

Returns whether this was a Login request.

View source

Returns

boolean

getIsPreview()

Since
3.2.1

Returns whether this is an element preview request.

View source

Returns

boolean

Example

getIsSingleActionRequest()

DEPRECATED

Deprecated in 3.2

Returns whether the current request is solely an action request.

View source

Returns

boolean

getIsSiteRequest()

Returns whether the front end site was requested. The result will always just be the opposite of whatever getIsCpRequest() returns.

View source

Returns

boolean – Whether the current request should be routed to the front-end site.

getPageNum()

Returns the requested page number.

View source

Returns

integer – The requested page number.

Example

getParam()

Returns the named parameter value from either GET or the request body. If the parameter does not exist, the second parameter to this method will be returned. See also:

View source

Arguments

  • $name (string) – The parameter name.
  • $defaultValue (mixed) – The default parameter value if the parameter does not exist.

Returns

mixed – The parameter value.

getPathInfo()

Returns the requested path, sans CP trigger and pagination info. If $returnRealPathInfo is returned, then \craft\web\parent::getPathInfo() will be returned. See also:

  • yii\web\UrlManager::processRequest()
  • yii\web\UrlRule::processRequest()

View source

Arguments

  • $returnRealPathInfo (boolean) – Whether the real path info should be returned instead.

Returns

string – The requested path, or the path info.

Throws

getQueryParam()

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

See also getBodyParam()View source

Arguments

  • $name (string) – The GET parameter name.
  • $defaultValue (mixed, null) – The default parameter value if the GET parameter does not exist.

Returns

mixed – The GET parameter value.

Example

getQueryParams()

Returns the request parameters given in the queryString.

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

View source

Returns

array – The request GET parameter values.

getQueryStringWithoutPath()

Returns the request’s query string, without the path parameter.

View source

Returns

string – The query string.

Example

getRemoteIP()

Returns the IP on the other end of this connection.

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

View source

Arguments

  • $filterOptions (integer) – Bitwise disjunction of flags that should be passed to filter_var() when validating the IP address. Options include FILTER_FLAG_IPV4, FILTER_FLAG_IPV6, FILTER_FLAG_NO_PRIV_RANGE, and FILTER_FLAG_NO_RES_RANGE.

Returns

string, null – Remote IP address, null if not available.

getRequiredBodyParam()

Returns the named request body parameter value, or bails on the request with a 400 error if that parameter doesn’t exist.

See also getBodyParam()View source

Arguments

  • $name (string) – The parameter name.

Returns

mixed – The parameter value

Throws

Example

getRequiredParam()

Returns the named parameter value from either GET or the request body, or bails on the request with a 400 error if that parameter doesn’t exist anywhere.

See also:

View source

Arguments

  • $name (string) – The parameter name.

Returns

mixed – The parameter value.

Throws

getRequiredQueryParam()

Returns the named GET parameter value, or bails on the request with a 400 error if that parameter doesn’t exist.

See also getQueryParam()View source

Arguments

  • $name (string) – The GET parameter name.

Returns

mixed – The GET parameter value.

Throws

Example

getSegment()

Returns a specific segment from the Craft path.

View source

Arguments

  • $num (integer) – Which segment to return (1-indexed).

Returns

string, null – The matching segment, or null if there wasn’t one.

Example

getSegments()

Returns the segments of the requested path.

TIP

Note that the segments will not include the CP trigger if it’s a CP request, or the page trigger or page number if it’s a paginated request.

View source

Returns

array – The Craft path’s segments.

Example

getToken()

Returns the token submitted with the request, if there is one.

View source

Returns

string, null – The token, or null if there isn’t one.

Throws

getUserIP()

Returns the user IP address.

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

View source

Arguments

  • $filterOptions (integer) – Bitwise disjunction of flags that should be passed to filter_var() when validating the IP address. Options include FILTER_FLAG_IPV4, FILTER_FLAG_IPV6, FILTER_FLAG_NO_PRIV_RANGE, and FILTER_FLAG_NO_RES_RANGE.

Returns

string, null – User IP address, null if not available

getValidatedBodyParam()

Validates and returns the named request body parameter value, or bails on the request with a 400 error if that parameter doesn’t pass validation.

See also getBodyParam()View source

Arguments

  • $name (string) – The parameter name.

Returns

mixed, null – The parameter value

Throws

Example

init()

Initializes the object.

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

View source

isMobileBrowser()

Returns whether the request is coming from a mobile browser. The detection script is provided by http://detectmobilebrowsers.com. It was last updated on 2014-11-24.

View source

Arguments

  • $detectTablets (boolean) – Whether tablets should be considered “mobile”.

Returns

boolean – Whether the request is coming from a mobile browser.

Example

regenCsrfToken()

Regenerates a CSRF token.

View source

setIsLivePreview()

Sets whether this is a Live Preview request.

View source

Arguments

Protected Methods

MethodDescription
createCsrfCookie()Creates a cookie with a randomly generated CSRF token.
csrfTokenValidForCurrentUser()Gets whether the CSRF token is valid for the current user or not
filterHeaders()Filters headers according to the trustedHosts.
generateCsrfToken()Generates an unmasked random token used to perform CSRF validation.
getIpValidator()Creates instance of \craft\web\IpValidator.
loadCookies()Converts $_COOKIE into an array of \craft\web\Cookie.
loadCsrfToken()Loads the CSRF token from cookie or session.
resolvePathInfo()Resolves the path info part of the currently requested URL.
resolveRequestUri()Resolves the request URI portion for the currently requested URL.

csrfTokenValidForCurrentUser()

Gets whether the CSRF token is valid for the current user or not

View source

Arguments

Returns

boolean

generateCsrfToken()

Generates an unmasked random token used to perform CSRF validation.

View source

Returns

string – The random token for CSRF validation.

Constants

ConstantDescription
CSRF_HEADERThe name of the HTTP header for sending CSRF token.
CSRF_MASK_LENGTHThe length of the CSRF token mask.