Skip to content

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

View source

Public Properties

PropertyDescription
_tokenstring, null
absoluteUrlstring – The currently requested absolute URL.
acceptableContentTypesarray – The content types ordered by the quality score.
acceptableLanguagesarray – The languages ordered by the preference level.
acceptsImageboolean
acceptsJsonboolean
actionSegmentsarray – The segments of the requested controller action path, if this is 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, object – 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 cookie.
csrfParamstring – The name of the token used to prevent CSRF.
csrfTokenstring – The token used to perform CSRF validation.
csrfTokenFromHeaderstring, null – 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 – The full requested path, including the control panel trigger and pagination info.
fullUristring
generalConfigcraft\config\GeneralConfig, array, string
hadTokenboolean
headersyii\web\HeaderCollection – The header collection.
hostInfostring, 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.
hostNamestring, null – Hostname part of the request URL (e.g. www.yiiframework.com).
ipHeadersstring[] – List of headers where proxies store the real client IP.
isActionRequestboolean – Whether a specific controller action was requested.
isAjaxboolean – Whether this is an AJAX (XMLHttpRequest) request.
isConsoleRequestboolean – The value indicating whether the current request is made via console.
isCpRequestboolean – Whether the control panel was requested.
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.
isGraphqlboolean – Whether the request’s MIME type is application/graphql
isHeadboolean – Whether this is a HEAD request.
isJsonboolean – Whether the request’s MIME type is application/json
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 – Whether this is an element preview request.
isPutboolean – Whether this is a PUT request.
isSecureConnectionboolean – If the request is sent via secure channel (https).
isSingleActionRequestboolean
isSiteRequestboolean – Whether the front end site was requested.
isWebAliasSetDynamicallyboolean
isWebrootAliasSetDynamicallyboolean
maxPageNuminteger – The highest page number that Craft should accept.
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.
mimeTypestring, null – The MIME type of the request, extracted from the request’s content type
normalizedContentTypestring, null
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.
pathstring – The requested path, sans control panel trigger and pagination info.
pathInfostring – Part of the request URL that is after the entry script and before the question mark.
portinteger – Port number for insecure requests.
portHeadersstring[] – List of headers where proxies store the real request port.
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 request’s query string, without the path parameter.
rawBodystring – The request body.
rawCookiesyii\web\CookieCollection – The cookie collection.
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 – The entry script file path.
scriptFilenamestring – The requested script name being used to access Craft (e.g. “index.php”).
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 segments of the requested path.
serverNamestring, null – Server name, null if not available.
serverPortinteger, null – Server port number, null if not available.
siteTokenstring, null – The token, or null if there isn’t one.
sitescraft\services\Sites, array, string, null
tokenstring – The token submitted with the request, if there is 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, null
Default value
null

See also getToken()

View source

acceptsImage

Type
boolean
Default value
null
Access
Read-only
Since
3.5.0

View source

acceptsJson

Type
boolean
Default value
null
Access
Read-only

View source

actionSegments

Type
array
Default value
null

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

View source

clientOs

Type
string
Default value
null
Access
Read-only

The OS the client is running.

View source

fullPath

Type
string
Default value
null

The full requested path, including the control panel trigger and pagination info.

View source

fullUri

Type
string
Default value
null
Access
Read-only
Since
3.5.0

View source

generalConfig

Type
craft\config\GeneralConfig, array, string
Default value
null
Since
3.5.10

View source

hadToken

Type
boolean
Default value
null
Access
Read-only
Since
3.6.0

View source

ipHeaders

Type
string[]
Default value
[ 'Client-IP', 'X-Forwarded-For', 'X-Forwarded', 'X-Cluster-Client-IP', 'Forwarded-For', 'Forwarded', ]

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.

View source

isActionRequest

Type
boolean
Default value
null

Whether a specific controller action was requested.

View source

isCpRequest

Type
boolean
Default value
null

Whether the control panel was requested.

View source

isGraphql

Type
boolean
Default value
null

Whether the request’s MIME type is application/graphql

View source

isJson

Type
boolean
Default value
null

Whether the request’s MIME type is application/json

View source

isLivePreview

Type
boolean
Default value
null

Whether this is a Live Preview request.

View source

isLoginRequest

Type
boolean
Default value
null
Access
Read-only
Since
3.2.0

View source

isPreview

Type
boolean
Default value
null

Whether this is an element preview request.

View source

isSingleActionRequest

Type
boolean
Default value
null
Access
Read-only

View source

isSiteRequest

Type
boolean
Default value
null

Whether the front end site was requested.

View source

maxPageNum

Type
integer
Default value
100000
Since
3.1.14

The highest page number that Craft should accept.

View source

mimeType

Type
string, null
Default value
null

The MIME type of the request, extracted from the request’s content type

View source

normalizedContentType

Type
string, null
Default value
null
Access
Read-only
Since
3.3.8

View source

pageNum

Type
integer
Default value
null

The requested page number.

View source

path

Type
string
Default value
null

The requested path, sans control panel trigger and pagination info.

View source

queryStringWithoutPath

Type
string
Default value
null

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

View source

rawCookies

Type
yii\web\CookieCollection
Default value
null
Access
Read-only
Since
3.5.0

The cookie collection.

View source

segments

Type
array
Default value
null

The segments of the requested path.

View source

siteToken

Type
string, null
Default value
null
Access
Read-only
Since
3.6.0

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

View source

sites

Type
craft\services\Sites, array, string, null
Default value
'sites'
Since
3.5.10

View source

token

Type
string
Default value
null

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

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 a component property.
__isset()Checks if a property is set, i.e. defined and not null.
__set()Sets the value of a component property.
__unset()Sets a component property to be 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.
checkIfActionRequest()Checks to see if this is an action request.
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.
getAcceptsImage()Returns whether the request will accept an image response.
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.
getFullUri()Returns the full requested URI.
getHadToken()Returns whether the request initially had a token.
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.
getIsGraphql()Returns whether the request’s MIME type is application/graphql.
getIsHead()Returns whether this is a HEAD request.
getIsJson()Returns whether the request’s MIME type is application/json.
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).
getMimeType()Returns the MIME type of the request, extracted from the request’s content type.
getNormalizedContentType()Returns the normalized content type.
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 control panel 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.
getRawCookies()Returns the “raw” cookie collection.
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 the 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. 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.
getSiteToken()Returns the site token submitted with the request, if there is one.
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 for this component.
hasValidSiteToken()Returns whether the request has a valid site token.
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.
resolve()Resolves the current request into a route and the associated parameters.
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.
setIsActionRequest()Overrides whether this request should be treated as an action request.
setIsConsoleRequest()Sets the value indicating whether the current request is made via command line.
setIsCpRequest()Sets whether the control panel was requested.
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.
setToken()Sets the token value.
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

checkIfActionRequest()

Since
3.7.0

Checks to see if this is an action request.

View source

Arguments

  • $force (boolean) – Whether to recheck even if we already know
  • $checkToken (boolean) – Whether to check if there’s a token on the request and use that.
  • $checkSpecialPaths (boolean) – Whether to check for special URIs that should route to controller actions

Returns

void

getAbsoluteUrl()

Returns the currently requested absolute URL.

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

WARNING

Don’t include the results of this method in places that will be cached, to avoid a cache poisoning attack.

View source

Returns

string – The currently requested absolute URL.

getAcceptsImage()

Since
3.5.0

Returns whether the request will accept an image response.

View source

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

php
// get $_POST['foo'], if it exists
$foo = Craft::$app->request->getBodyParam('foo');

// get $_POST['foo']['bar'], if it exists
$bar = Craft::$app->request->getBodyParam('foo.bar');
twig
{# get $_POST['foo'], if it exists #}
{% set foo = craft.app.request.getBodyParam('foo') %}

{# get $_POST['foo']['bar'], if it exists #}
{% set bar = craft.app.request.getBodyParam('foo.bar') %}

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, object – 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

php
$clientOs = Craft::$app->request->clientOs;
twig
{% set clientOs = craft.app.request.clientOs %}

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

getFullUri()

Since
3.5.0

Returns the full requested URI.

View source

Returns

string

getHadToken()

Since
3.6.0

Returns whether the request initially had a token.

View source

Returns

boolean

Throws

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 control panel trigger.

View source

Returns

boolean – Whether the current request should be routed to the control panel.

getIsGraphql()

Since
3.5.0

Returns whether the request’s MIME type is application/graphql.

View source

Returns

boolean

getIsJson()

Since
3.5.0

Returns whether the request’s MIME type is application/json.

View source

Returns

boolean

getIsLivePreview()

Returns whether this is a Live Preview request.

TIP

As of Craft 3.2, entries use a new previewing system, so this won’t return true for them. Check getIsPreview() instead for entries.

View source

Returns

boolean – Whether this is a Live Preview request.


Example

php
$isLivePreview = Craft::$app->request->isLivePreview;
twig
{% set isLivePreview = craft.app.request.isLivePreview %}

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.

TIP

This will only return true when previewing entries at the moment. For all other element types, check getIsLivePreview().

View source

Returns

boolean


Example

php
$isPreviewRequest = Craft::$app->request->isPreview;
twig
{% set isPreviewRequest = craft.app.request.isPreview %}

getIsSingleActionRequest()

DEPRECATED

Deprecated in 3.2.0

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.

getMimeType()

Since
3.5.0

Returns the MIME type of the request, extracted from the request’s content type.

View source

Returns

string, null

getNormalizedContentType()

Since
3.3.8

Returns the normalized content type.

View source

Returns

string, null

getPageNum()

Returns the requested page number.

View source

Returns

integer – The requested page number.


Example

php
$page = Craft::$app->request->pageNum;
twig
{% set page = craft.app.request.pageNum %}

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 control panel trigger and pagination info.

If $returnRealPathInfo is returned, then yii\web\Request::getPathInfo() will be returned.

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

php
// get $_GET['foo'], if it exists
$foo = Craft::$app->request->getQueryParam('foo');

// get $_GET['foo']['bar'], if it exists
$bar = Craft::$app->request->getQueryParam('foo.bar');
twig
{# get $_GET['foo'], if it exists #}
{% set foo = craft.app.request.getQueryParam('foo') %}

{# get $_GET['foo']['bar'], if it exists #}
{% set bar = craft.app.request.getQueryParam('foo.bar') %}

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

php
$queryString = Craft::$app->request->queryStringWithoutPath;
twig
{% set queryString = craft.app.request.queryStringWithoutPath %}

getRawCookies()

Since
3.5.0

Returns the “raw” cookie collection.

Works similar to getCookies(), but these cookies won’t go through validation, and their values won’t be hashed.

View source

Returns

yii\web\CookieCollection – The cookie collection.

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

php
// get required $_POST['foo']
$foo = Craft::$app->request->getRequiredBodyParam('foo');

// get required $_POST['foo']['bar']
$bar = Craft::$app->request->getRequiredBodyParam('foo.bar');
twig
{# get required $_POST['foo'] #}
{% set foo = craft.app.request.getRequiredBodyParam('foo') %}

{# get required $_POST['foo']['bar'] #}
{% set bar = craft.app.request.getRequiredBodyParam('foo.bar') %}

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

php
// get required $_GET['foo']
$foo = Craft::$app->request->getRequiredQueryParam('foo');

// get required $_GET['foo']['bar']
$bar = Craft::$app->request->getRequiredQueryParam('foo.bar');
twig
{# get required$_GET['foo'] #}
{% set foo = craft.app.request.getRequiredQueryParam('foo') %}

{# get required $_GET['foo']['bar'] #}
{% set bar = craft.app.request.getRequiredQueryParam('foo.bar') %}

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

php
$firstSegment = Craft::$app->request->getSegment(1);
twig
{% set firstSegment = craft.app.request.getSegment(1) %}

getSegments()

Returns the segments of the requested path.

TIP

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

View source

Returns

array – The Craft path’s segments.


Example

php
$segments = Craft::$app->request->segments;
twig
{% set segments = craft.app.request.segments %}

getSiteToken()

Since
3.6.0

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

Tokens must be sent either as a query string param named after the config3:siteToken config setting (siteToken by default), or an X-Craft-Site-Token HTTP header on the request.

View source

Returns

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

getToken()

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

Tokens must be sent either as a query string param named after the config3:tokenParam config setting (token by default), or an X-Craft-Token HTTP header on the request.

See also:

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

php
// get validated $_POST['foo']
$foo = Craft::$app->request->getValidatedBodyParam('foo');

// get validated $_POST['foo']['bar']
$bar = Craft::$app->request->getValidatedBodyParam('foo.bar');
twig
{# get validated $_POST['foo'] #}
{% set foo = craft.app.request.getValidatedBodyParam('foo') %}

{# get validated $_POST['foo']['bar'] #}
{% set bar = craft.app.request.getValidatedBodyParam('foo.bar') %}

hasValidSiteToken()

Since
3.8.6

Returns whether the request has a valid site token.

View source

Returns

boolean

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

php
$isMobileBrowser = Craft::$app->request->isMobileBrowser();
twig
{% set isMobileBrowser = craft.app.request.isMobileBrowser() %}

regenCsrfToken()

Regenerates a CSRF token.

View source

setIsActionRequest()

Since
3.7.8

Overrides whether this request should be treated as an action request.

See also checkIfActionRequest()View source

Arguments

setIsCpRequest()

Since
3.5.0

Sets whether the control panel was requested.

View source

Arguments

setIsLivePreview()

Sets whether this is a Live Preview request.

View source

Arguments

setToken()

Since
3.6.0

Sets the token value.

View source

Arguments

  • $token (?string)

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 yii\validators\IpValidator.
getSecureForwardedHeaderParts()Returns decoded forwarded header
getSecureForwardedHeaderTrustedPart()Gets first Forwarded header value for token
getSecureForwardedHeaderTrustedParts()Gets only trusted Forwarded header parts
getTrustedHeaders()Trusted headers according to the trustedHosts.
getUserIpFromIpHeader()Return user IP's from IP header.
getUserIpFromIpHeaders()Returns the user IP address from ipHeaders.
loadCookies()Converts $_COOKIE into an array of yii\web\Cookie.
loadCsrfToken()Loads the CSRF token from cookie or session.
loadRawCookies()Converts any invalid cookies in $_COOKIE into an array of yii\web\Cookie objects.
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.

loadRawCookies()

Since
3.5.0

Converts any invalid cookies in $_COOKIE into an array of yii\web\Cookie objects.

View source

Returns

yii\web\Cookie

Constants

ConstantDescription
CP_PATH_LOGIN
CP_PATH_LOGOUT
CP_PATH_SET_PASSWORD
CP_PATH_UPDATE
CP_PATH_VERIFY_EMAIL
CSRF_HEADERThe name of the HTTP header for sending CSRF token.
CSRF_MASK_LENGTHThe length of the CSRF token mask.