Request

Type
Class
Namespace
craft\web
Inherits
craft\web\Request » yii\web\Request (opens new window) » yii\base\Request (opens new window) » yii\base\Component (opens new window) » yii\base\BaseObject (opens new window)
Implements
yii\base\Configurable (opens new window)
Uses traits
craft\base\RequestTrait
Since
3.0.0

View source (opens new window)

# Public Properties

Property Description
_token string (opens new window), false (opens new window)
absoluteUrl string (opens new window) – The currently requested absolute URL.
acceptableContentTypes (opens new window) array (opens new window) – The content types ordered by the quality score.
acceptableLanguages (opens new window) array (opens new window) – The languages ordered by the preference level.
acceptsImage boolean (opens new window)
acceptsJson boolean (opens new window)
actionSegments array (opens new window), null (opens new window) – The action path segments, or null if this isn’t an action request.
authCredentials (opens new window) array (opens new window) – That contains exactly two elements: - 0: the username sent via HTTP authentication, null if the username is not given - 1: the password sent via HTTP authentication, null if the password is not given
authPassword (opens new window) string (opens new window), null (opens new window) – The password sent via HTTP authentication, null if the password is not given
authUser (opens new window) string (opens new window), null (opens new window) – The username sent via HTTP authentication, null if the username is not given
baseUrl (opens new window) string (opens new window) – The relative URL for the application
behaviors (opens new window) yii\base\Behavior (opens new window) – List of behaviors attached to this component
bodyParams array (opens new window) – The request parameters given in the request body.
clientOs string (opens new window) – The OS the client is running.
contentType (opens new window) string (opens new window) – Request content-type.
cookieValidationKey (opens new window) string (opens new window) – A secret key used for cookie validation.
cookies (opens new window) yii\web\CookieCollection (opens new window) – The cookie collection.
csrfCookie (opens new window) array (opens new window) – The configuration for creating the CSRF cookie (opens new window).
csrfParam (opens new window) string (opens new window) – The name of the token used to prevent CSRF.
csrfToken string (opens new window) – The token used to perform CSRF validation.
csrfTokenFromHeader (opens new window) string (opens new window) – The CSRF token sent via CSRF_HEADER (opens new window) by browser.
eTags (opens new window) array (opens new window) – The entity tags
enableCookieValidation (opens new window) boolean (opens new window) – Whether cookies should be validated to ensure they are not tampered.
enableCsrfCookie (opens new window) boolean (opens new window) – Whether to use cookie to persist CSRF token.
enableCsrfValidation (opens new window) boolean (opens new window) – Whether to enable CSRF (Cross-Site Request Forgery) validation.
fullPath string (opens new window)
fullUri string (opens new window)
generalConfig craft\config\GeneralConfig, array (opens new window), string (opens new window)
headers (opens new window) yii\web\HeaderCollection (opens new window) – The header collection
hostInfo (opens new window) string (opens new window), null (opens new window) – Schema and hostname part (with port number if needed) of the request URL (e.g. `http://www.
hostName (opens new window) string (opens new window), null (opens new window) – Hostname part of the request URL (e.g. `www.
ipHeaders string (opens new window)[] – List of headers where proxies store the real client IP.
isActionRequest boolean (opens new window) – Whether the current request should be routed to a controller action.
isAjax (opens new window) boolean (opens new window) – Whether this is an AJAX (XMLHttpRequest) request.
isConsoleRequest (opens new window) boolean (opens new window) – The value indicating whether the current request is made via console
isCpRequest boolean (opens new window) – Whether the current request should be routed to the control panel.
isDelete (opens new window) boolean (opens new window) – Whether this is a DELETE request.
isFlash (opens new window) boolean (opens new window) – Whether this is an Adobe Flash or Adobe Flex request.
isGet (opens new window) boolean (opens new window) – Whether this is a GET request.
isGraphql boolean (opens new window)
isHead (opens new window) boolean (opens new window) – Whether this is a HEAD request.
isJson boolean (opens new window)
isLivePreview boolean (opens new window) – Whether this is a Live Preview request.
isLoginRequest boolean (opens new window)
isOptions (opens new window) boolean (opens new window) – Whether this is a OPTIONS request.
isPatch (opens new window) boolean (opens new window) – Whether this is a PATCH request.
isPjax (opens new window) boolean (opens new window) – Whether this is a PJAX request
isPost (opens new window) boolean (opens new window) – Whether this is a POST request.
isPreview boolean (opens new window)
isPut (opens new window) boolean (opens new window) – Whether this is a PUT request.
isSecureConnection (opens new window) boolean (opens new window) – If the request is sent via secure channel (https)
isSingleActionRequest boolean (opens new window)
isSiteRequest boolean (opens new window) – Whether the current request should be routed to the front-end site.
isWebAliasSetDynamically boolean (opens new window)
isWebrootAliasSetDynamically boolean (opens new window)
maxPageNum integer (opens new window) – The highest page number that Craft should accept.
method (opens new window) string (opens new window) – Request method, such as GET, POST, HEAD, PUT, PATCH, DELETE.
methodParam (opens new window) string (opens new window) – The name of the POST parameter that is used to indicate if a request is a PUT, PATCH or DELETE request tunneled through POST.
mimeType string (opens new window), null (opens new window)
normalizedContentType string (opens new window), null (opens new window)
origin (opens new window) string (opens new window), null (opens new window) – URL origin of a CORS request, null if not available.
pageNum integer (opens new window) – The requested page number.
parsers (opens new window) array (opens new window) – The parsers for converting the raw HTTP request body into bodyParams (opens new window).
pathInfo string (opens new window) – The requested path, or the path info.
port (opens new window) integer (opens new window) – Port number for insecure requests.
preferredLanguage (opens new window) string (opens new window) – The language that the application should use.
queryParams array (opens new window) – The request GET parameter values.
queryString (opens new window) string (opens new window) – Part of the request URL that is after the question mark
queryStringWithoutPath string (opens new window) – The query string.
rawBody (opens new window) string (opens new window) – The request body
rawCookies yii\web\CookieCollection (opens new window) – The cookie collection.
referrer (opens new window) string (opens new window), null (opens new window) – URL referrer, null if not available
remoteHost (opens new window) string (opens new window), null (opens new window) – Remote host name, null if not available
remoteIP string (opens new window), null (opens new window) – Remote IP address, null if not available.
scriptFile (opens new window) string (opens new window) – Entry script file path (processed w/ realpath())
scriptFilename string (opens new window)
scriptUrl (opens new window) string (opens new window) – The relative URL of the entry script.
secureHeaders (opens new window) array (opens new window) – Lists of headers that are, by default, subject to the trusted host configuration.
securePort (opens new window) integer (opens new window) – Port number for secure requests.
secureProtocolHeaders (opens new window) array (opens new window) – List of headers to check for determining whether the connection is made via HTTPS.
segments array (opens new window) – The Craft path’s segments.
serverName (opens new window) string (opens new window) – Server name, null if not available
serverPort (opens new window) integer (opens new window), null (opens new window) – Server port number, null if not available
sites craft\services\Sites, array (opens new window), string (opens new window), null (opens new window)
token string (opens new window), null (opens new window) – The token, or null if there isn’t one.
trustedHosts (opens new window) array (opens new window) – The configuration for trusted security related headers.
url (opens new window) string (opens new window) – The currently requested relative URL.
userAgent (opens new window) string (opens new window), null (opens new window) – User agent, null if not available
userHost (opens new window) string (opens new window), null (opens new window) – User host name, null if not available
userIP string (opens new window), null (opens new window) – User IP address, null if not available

# _token

Type
string (opens new window), false (opens new window)
Default value
null

See also getToken()

View source (opens new window)

# absoluteUrl

Type
string (opens new window)
Default value
null
Access
Read-only

The currently requested absolute URL.

View source (opens new window)

# acceptsImage

Type
boolean (opens new window)
Default value
null
Access
Read-only
Since
3.5.0

View source (opens new window)

# acceptsJson

Type
boolean (opens new window)
Default value
null
Access
Read-only

View source (opens new window)

# actionSegments

Type
array (opens new window), null (opens new window)
Default value
null
Access
Read-only

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

View source (opens new window)

# bodyParams

Type
array (opens new window)
Default value
null

The request parameters given in the request body.

View source (opens new window)

# clientOs

Type
string (opens new window)
Default value
null
Access
Read-only

The OS the client is running.

View source (opens new window)

# csrfToken

Type
string (opens new window)
Default value
null
Access
Read-only

The token used to perform CSRF validation.

View source (opens new window)

# fullPath

Type
string (opens new window)
Default value
null
Access
Read-only

View source (opens new window)

# fullUri

Type
string (opens new window)
Default value
null
Access
Read-only
Since
3.5.0

View source (opens new window)

# generalConfig

Type
craft\config\GeneralConfig, array (opens new window), string (opens new window)
Default value
null
Since
3.5.10

View source (opens new window)

# ipHeaders

Type
string (opens new window)[]
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 (opens new window) list. The match of header names is case-insensitive.

View source (opens new window)

# isActionRequest

Type
boolean (opens new window)
Default value
null
Access
Read-only

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

View source (opens new window)

# isCpRequest

Type
boolean (opens new window)
Default value
null
Access
Read-only

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

View source (opens new window)

# isGraphql

Type
boolean (opens new window)
Default value
null
Access
Read-only
Since
3.5.0

View source (opens new window)

# isJson

Type
boolean (opens new window)
Default value
null
Access
Read-only
Since
3.5.0

View source (opens new window)

# isLivePreview

Type
boolean (opens new window)
Default value
null

Whether this is a Live Preview request.

View source (opens new window)

# isLoginRequest

Type
boolean (opens new window)
Default value
null
Access
Read-only
Since
3.2.0

View source (opens new window)

# isPreview

Type
boolean (opens new window)
Default value
null
Access
Read-only
Since
3.2.1

View source (opens new window)

# isSingleActionRequest

Type
boolean (opens new window)
Default value
null
Access
Read-only

View source (opens new window)

# isSiteRequest

Type
boolean (opens new window)
Default value
null
Access
Read-only

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

View source (opens new window)

# maxPageNum

Type
integer (opens new window)
Default value
100000
Since
3.1.14

The highest page number that Craft should accept.

View source (opens new window)

# mimeType

Type
string (opens new window), null (opens new window)
Default value
null
Access
Read-only
Since
3.5.0

View source (opens new window)

# normalizedContentType

Type
string (opens new window), null (opens new window)
Default value
null
Access
Read-only
Since
3.3.8

View source (opens new window)

# pageNum

Type
integer (opens new window)
Default value
null
Access
Read-only

The requested page number.

View source (opens new window)

# pathInfo

Type
string (opens new window)
Default value
null

The requested path, or the path info.

View source (opens new window)

# queryParams

Type
array (opens new window)
Default value
null

The request GET parameter values.

View source (opens new window)

# queryStringWithoutPath

Type
string (opens new window)
Default value
null
Access
Read-only

The query string.

View source (opens new window)

# rawCookies

Type
yii\web\CookieCollection (opens new window)
Default value
null
Access
Read-only
Since
3.5.0

The cookie collection.

View source (opens new window)

# remoteIP

Type
string (opens new window), null (opens new window)
Default value
null
Access
Read-only

Remote IP address, null if not available.

View source (opens new window)

# segments

Type
array (opens new window)
Default value
null
Access
Read-only

The Craft path’s segments.

View source (opens new window)

# sites

Type
craft\services\Sites, array (opens new window), string (opens new window), null (opens new window)
Default value
'sites'
Since
3.5.10

View source (opens new window)

# token

Type
string (opens new window), null (opens new window)
Default value
null
Access
Read-only

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

View source (opens new window)

# userIP

Type
string (opens new window), null (opens new window)
Default value
null
Access
Read-only

User IP address, null if not available

View source (opens new window)

# Public Methods

Method Description
__call() (opens new window) Calls the named method which is not a class method.
__clone() (opens new window) This method is called after the object is created by cloning an existing one.
__construct() (opens new window) Constructor.
__get() (opens new window) Returns the value of an object property.
__isset() (opens new window) Checks if a property is set, i.e. defined and not null.
__set() (opens new window) Sets value of an object property.
__unset() (opens new window) Sets an object property to null.
accepts() Returns whether the request will accept a given content type3
attachBehavior() (opens new window) Attaches a behavior to this component.
attachBehaviors() (opens new window) Attaches a list of behaviors to the component.
behaviors() (opens new window) Returns a list of behaviors that this component should behave as.
canGetProperty() (opens new window) Returns a value indicating whether a property can be read.
canSetProperty() (opens new window) Returns a value indicating whether a property can be set.
className() (opens new window) Returns the fully qualified name of this class.
detachBehavior() (opens new window) Detaches a behavior from the component.
detachBehaviors() (opens new window) Detaches all behaviors from the component.
ensureBehaviors() (opens new window) Makes sure that the behaviors declared in behaviors() (opens new window) are attached to this component.
get() (opens new window) 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() (opens new window) Returns the content types acceptable by the end user.
getAcceptableLanguages() (opens new window) 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() (opens new window)
getAuthPassword() (opens new window)
getAuthUser() (opens new window)
getBaseUrl() (opens new window) Returns the relative URL for the application.
getBehavior() (opens new window) Returns the named behavior object.
getBehaviors() (opens new window) 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() (opens new window) Returns request content-type The Content-Type header field indicates the MIME type of the data contained in getRawBody() (opens new window) or, in the case of the HEAD method, the media type that would have been sent had the request been a GET.
getCookies() (opens new window) Returns the cookie collection.
getCsrfToken() Returns the token used to perform CSRF validation.
getCsrfTokenFromHeader() (opens new window)
getETags() (opens new window) 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.
getHeaders() (opens new window) Returns the header collection.
getHostInfo() (opens new window) Returns the schema and host part of the current request URL.
getHostName() (opens new window) Returns the host part of the current request URL.
getIsActionRequest() Returns whether a specific controller action was requested.
getIsAjax() (opens new window) Returns whether this is an AJAX (XMLHttpRequest) request.
getIsConsoleRequest() (opens new window) Returns a value indicating whether the current request is made via command line.
getIsCpRequest() Returns whether the control panel was requested.
getIsDelete() (opens new window) Returns whether this is a DELETE request.
getIsFlash() (opens new window) Returns whether this is an Adobe Flash or Flex request.
getIsGet() (opens new window) Returns whether this is a GET request.
getIsGraphql() Returns whether the request’s MIME type is application/graphql.
getIsHead() (opens new window) 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() (opens new window) Returns whether this is an OPTIONS request.
getIsPatch() (opens new window) Returns whether this is a PATCH request.
getIsPjax() (opens new window) Returns whether this is a PJAX request.
getIsPost() (opens new window) Returns whether this is a POST request.
getIsPreview() Returns whether this is an element preview request.
getIsPut() (opens new window) Returns whether this is a PUT request.
getIsSecureConnection() (opens new window) 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() (opens new window) 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() (opens new window) 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() (opens new window) Returns the port to use for insecure requests.
getPreferredLanguage() (opens new window) 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 (opens new window).
getQueryString() (opens new window) Returns part of the request URL that is after the question mark.
getQueryStringWithoutPath() Returns the request’s query string, without the path parameter.
getRawBody() (opens new window) Returns the raw HTTP request body.
getRawCookies() Returns the “raw” cookie collection.
getReferrer() (opens new window) Returns the URL referrer.
getRemoteHost() (opens new window) 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() (opens new window) Returns entry script file path.
getScriptFilename() Returns the requested script name being used to access Craft (e.g. “index.php”).
getScriptUrl() (opens new window) Returns the relative URL of the entry script.
getSecurePort() (opens new window) 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() (opens new window) Returns the server name.
getServerPort() (opens new window) Returns the server port number.
getToken() Returns the token submitted with the request, if there is one.
getUrl() (opens new window) Returns the currently requested relative URL.
getUserAgent() (opens new window) Returns the user agent.
getUserHost() (opens new window) 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() (opens new window) Returns a value indicating whether there is any handler attached to the named event.
hasMethod() (opens new window) Returns a value indicating whether a method is defined.
hasProperty() (opens new window) 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() (opens new window) Detaches an existing event handler from this component.
on() (opens new window) Attaches an event handler to an event.
parseAcceptHeader() (opens new window) Parses the given Accept (or Accept-Language) header.
post() (opens new window) 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() (opens new window) Sets the acceptable content types.
setAcceptableLanguages() (opens new window)
setBaseUrl() (opens new window) Sets the relative URL for the application.
setBodyParams() (opens new window) Sets the request body parameters.
setHostInfo() (opens new window) Sets the schema and host part of the application URL.
setIsConsoleRequest() (opens new window) 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() (opens new window) Sets the path info of the current request.
setPort() (opens new window) Sets the port to use for insecure requests.
setQueryParams() (opens new window) Sets the request queryString (opens new window) parameters.
setRawBody() (opens new window) Sets the raw HTTP request body, this method is mainly used by test scripts to simulate raw HTTP requests.
setScriptFile() (opens new window) Sets the entry script file path.
setScriptUrl() (opens new window) Sets the relative URL for the application entry script.
setSecurePort() (opens new window) Sets the port to use for secure requests.
setUrl() (opens new window) Sets the currently requested relative URL.
trigger() (opens new window) Triggers an event.
validateCsrfToken() (opens new window) Performs the CSRF validation.

# accepts()

Returns whether the request will accept a given content type3

View source (opens new window)

Arguments

Returns

boolean (opens new window)

# getAbsoluteUrl()

Returns the currently requested absolute URL.

This is a shortcut to the concatenation of hostInfo (opens new window) and url (opens new window).

WARNING

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

View source (opens new window)

Returns

string (opens new window) – The currently requested absolute URL.

# getAcceptsImage()

Since
3.5.0

Returns whether the request will accept an image response.

View source (opens new window)

Returns

boolean (opens new window)

# getAcceptsJson()

Returns whether the request will accept a JSON response.

View source (opens new window)

Returns

boolean (opens new window)

# getActionSegments()

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

View source (opens new window)

Returns

array (opens new window), null (opens new window) – 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 (opens new window)

Arguments

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

Returns

mixed – The parameter value

Example

// 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');

# getBodyParams()

Returns the request parameters given in the request body.

Request parameters are determined using the parsers configured in parsers (opens new window) property. If no parsers are configured for the current contentType (opens new window) it uses the PHP function mb_parse_str() to parse the request body (opens new window).

View source (opens new window)

Returns

array (opens new window) – 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 (opens new window)

Returns

string (opens new window) – The OS the client is running.

Example

$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 (opens new window). 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 (opens new window)

Arguments

  • $regenerate (boolean (opens new window)) – 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 (opens new window) – 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 (opens new window)

Returns

string (opens new window)

# getFullUri()

Since
3.5.0

Returns the full requested URI.

View source (opens new window)

Returns

string (opens new window)

# 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 (opens new window)
  • 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 (opens new window)

Returns

boolean (opens new window) – 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 (opens new window).

View source (opens new window)

Returns

boolean (opens new window) – 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 (opens new window)

Returns

boolean (opens new window)

# getIsJson()

Since
3.5.0

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

View source (opens new window)

Returns

boolean (opens new window)

# 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 (opens new window)

Returns

boolean (opens new window) – Whether this is a Live Preview request.

Example

$isLivePreview = Craft::$app->request->isLivePreview;

# getIsLoginRequest()

Since
3.2.0

Returns whether this was a Login request.

View source (opens new window)

Returns

boolean (opens new window)

# 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 (opens new window)

Returns

boolean (opens new window)

Example

$isPreviewRequest = Craft::$app->request->isPreview;

# getIsSingleActionRequest()

DEPRECATED

Deprecated in 3.2.0

Returns whether the current request is solely an action request.

View source (opens new window)

Returns

boolean (opens new window)

# getIsSiteRequest()

Returns whether the front end site was requested.

The result will always just be the opposite of whatever getIsCpRequest() returns.

View source (opens new window)

Returns

boolean (opens new window) – 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 (opens new window)

Returns

string (opens new window), null (opens new window)

# getNormalizedContentType()

Since
3.3.8

Returns the normalized content type.

View source (opens new window)

Returns

string (opens new window), null (opens new window)

# getPageNum()

Returns the requested page number.

View source (opens new window)

Returns

integer (opens new window) – The requested page number.

Example

$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 (opens new window)

Arguments

  • $name (string (opens new window)) – 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() (opens new window) will be returned.

View source (opens new window)

Arguments

Returns

string (opens new window) – 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 (opens new window)

Arguments

Returns

mixed – The GET parameter value.

Example

// 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');

# getQueryParams()

Returns the request parameters given in the queryString (opens new window).

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

View source (opens new window)

Returns

array (opens new window) – The request GET parameter values.

# getQueryStringWithoutPath()

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

View source (opens new window)

Returns

string (opens new window) – The query string.

Example

$queryString = Craft::$app->request->queryStringWithoutPath;

# getRawCookies()

Since
3.5.0

Returns the “raw” cookie collection.

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

View source (opens new window)

Returns

yii\web\CookieCollection (opens new window) – 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 (opens new window)

Arguments

Returns

string (opens new window), null (opens new window) – 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 (opens new window)

Arguments

Returns

mixed – The parameter value

Throws

Example

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

// get required $_POST['foo']['bar']
$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 (opens new window)

Arguments

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 (opens new window)

Arguments

Returns

mixed – The GET parameter value.

Throws

Example

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

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

# getSegment()

Returns a specific segment from the Craft path.

View source (opens new window)

Arguments

Returns

string (opens new window), null (opens new window) – The matching segment, or null if there wasn’t one.

Example

$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 (opens new window) if it’s a control panel request, or the page trigger (opens new window) or page number if it’s a paginated request.

View source (opens new window)

Returns

array (opens new window) – The Craft path’s segments.

Example

$segments = Craft::$app->request->segments;

# 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 (opens new window) config setting (token by default), or an X-Craft-Token HTTP header on the request.

See also:

View source (opens new window)

Returns

string (opens new window), null (opens new window) – 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 (opens new window)

Arguments

Returns

string (opens new window), null (opens new window) – 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 (opens new window)

Arguments

Returns

mixed, null (opens new window) – The parameter value

Throws

Example

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

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

# 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 (opens new window)

# 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 (opens new window)

Arguments

Returns

boolean (opens new window) – Whether the request is coming from a mobile browser.

Example

$isMobileBrowser = Craft::$app->request->isMobileBrowser();

# regenCsrfToken()

Regenerates a CSRF token.

View source (opens new window)

# setIsCpRequest()

Since
3.5.0

Sets whether the control panel was requested.

View source (opens new window)

Arguments

# setIsLivePreview()

Sets whether this is a Live Preview request.

View source (opens new window)

Arguments

# Protected Methods

Method Description
createCsrfCookie() (opens new window) Creates a cookie with a randomly generated CSRF token.
csrfTokenValidForCurrentUser() Gets whether the CSRF token is valid for the current user or not
filterHeaders() (opens new window) Filters headers according to the trustedHosts (opens new window).
generateCsrfToken() Generates an unmasked random token used to perform CSRF validation.
getIpValidator() (opens new window) Creates instance of yii\validators\IpValidator (opens new window).
getSecureForwardedHeaderParts() (opens new window) Returns decoded forwarded header
getSecureForwardedHeaderTrustedPart() (opens new window) Gets first Forwarded header value for token
getSecureForwardedHeaderTrustedParts() (opens new window) Gets only trusted Forwarded header parts
getTrustedHeaders() (opens new window) Trusted headers according to the trustedHosts (opens new window).
getUserIpFromIpHeader() (opens new window) Return user IP's from IP header.
getUserIpFromIpHeaders() (opens new window) Returns the user IP address from ipHeaders (opens new window).
loadCookies() (opens new window) Converts $_COOKIE into an array of yii\web\Cookie (opens new window).
loadCsrfToken() (opens new window) Loads the CSRF token from cookie or session.
loadRawCookies() Converts any invalid cookies in $_COOKIE into an array of yii\web\Cookie (opens new window) objects.
resolvePathInfo() (opens new window) Resolves the path info part of the currently requested URL.
resolveRequestUri() (opens new window) 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 (opens new window)

Arguments

Returns

boolean (opens new window)

# generateCsrfToken()

Generates an unmasked random token used to perform CSRF validation.

View source (opens new window)

Returns

string (opens new window) – The random token for CSRF validation.

# loadRawCookies()

Since
3.5.0

Converts any invalid cookies in $_COOKIE into an array of yii\web\Cookie (opens new window) objects.

View source (opens new window)

Returns

yii\web\Cookie (opens new window)

# Constants

Constant Description
CP_PATH_LOGIN
CP_PATH_LOGOUT
CP_PATH_SET_PASSWORD
CP_PATH_UPDATE
CP_PATH_VERIFY_EMAIL
CSRF_HEADER The name of the HTTP header for sending CSRF token.
CSRF_MASK_LENGTH The length of the CSRF token mask.