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
Public Properties
Property | Description |
---|---|
_token | string, null |
absoluteUrl | string – The currently requested absolute URL. |
acceptableContentTypes | array – The content types ordered by the quality score. |
acceptableLanguages | array – The languages ordered by the preference level. |
acceptsImage | boolean |
acceptsJson | boolean |
actionSegments | array – The segments of the requested controller action path, if this is an action request. |
authCredentials | array – That contains exactly two elements: - 0: the username sent via HTTP authentication, null if the username is not given - 1: the password sent via HTTP authentication, null if the password is not given. |
authPassword | string, null – The password sent via HTTP authentication, null if the password is not given. |
authUser | string, null – The username sent via HTTP authentication, null if the username is not given. |
baseUrl | string – The relative URL for the application. |
bearerToken | string, null |
behaviors | yii\base\Behavior – List of behaviors attached to this component. |
bodyParams | array, object – The request parameters given in the request body. |
clientOs | string – The OS the client is running. |
contentType | string – Request content-type. |
cookieValidationKey | string – A secret key used for cookie validation. |
cookies | yii\web\CookieCollection – The cookie collection. |
csrfCookie | array – The configuration for creating the CSRF cookie. |
csrfParam | string – The name of the token used to prevent CSRF. |
csrfToken | string – The token used to perform CSRF validation. |
csrfTokenFromHeader | string, null – The CSRF token sent via CSRF_HEADER by browser. |
eTags | array – The entity tags. |
enableCookieValidation | boolean – Whether cookies should be validated to ensure they are not tampered. |
enableCsrfCookie | boolean – Whether to use cookie to persist CSRF token. |
enableCsrfValidation | boolean – Whether to enable CSRF (Cross-Site Request Forgery) validation. |
fullPath | string – The full requested path, including the control panel trigger and pagination info. |
fullUri | string |
generalConfig | craft\config\GeneralConfig, array, string |
hadToken | boolean |
headers | yii\web\HeaderCollection – The header collection. |
hostInfo | string, null – Schema and hostname part (with port number if needed) of the request URL (e.g. https://www.yiiframework.com ), null if can't be obtained from $_SERVER and wasn't set. |
hostName | string, null – Hostname part of the request URL (e.g. www.yiiframework.com ). |
ipHeaders | string[] – List of headers where proxies store the real client IP. |
isActionRequest | boolean – Whether a specific controller action was requested. |
isAjax | boolean – Whether this is an AJAX (XMLHttpRequest) request. |
isConsoleRequest | boolean – The value indicating whether the current request is made via console. |
isCpRequest | boolean – Whether the control panel was requested. |
isDelete | boolean – Whether this is a DELETE request. |
isFlash | boolean – Whether this is an Adobe Flash or Adobe Flex request. |
isGet | boolean – Whether this is a GET request. |
isGraphql | boolean – Whether the request’s MIME type is application/graphql |
isHead | boolean – Whether this is a HEAD request. |
isJson | boolean – Whether the request’s MIME type is application/json |
isLivePreview | boolean – Whether this is a Live Preview request. |
isLoginRequest | boolean |
isOptions | boolean – Whether this is a OPTIONS request. |
isPatch | boolean – Whether this is a PATCH request. |
isPjax | boolean – Whether this is a PJAX request. |
isPost | boolean – Whether this is a POST request. |
isPreview | boolean – Whether this is an element preview request. |
isPut | boolean – Whether this is a PUT request. |
isSecureConnection | boolean – If the request is sent via secure channel (https). |
isSiteRequest | boolean – Whether the front end site was requested. |
isWebAliasSetDynamically | boolean |
isWebRequest | boolean – Whether this is a web request. |
isWebrootAliasSetDynamically | boolean |
maxPageNum | integer – The highest page number that Craft should accept. |
method | string – Request method, such as GET, POST, HEAD, PUT, PATCH, DELETE. |
methodParam | string – The name of the POST parameter that is used to indicate if a request is a PUT, PATCH or DELETE request tunneled through POST. |
mimeType | string, null – The MIME type of the request, extracted from the request’s content type |
normalizedContentType | string, null |
origin | string, null – URL origin of a CORS request, null if not available. |
pageNum | integer – The requested page number. |
parsers | array – The parsers for converting the raw HTTP request body into bodyParams. |
pathInfo | string – Part of the request URL that is after the entry script and before the question mark. |
port | integer – Port number for insecure requests. |
portHeaders | string[] – List of headers where proxies store the real request port. |
preferredLanguage | string – The language that the application should use. |
queryParams | array – The request GET parameter values. |
queryParamsWithoutPath | array |
queryString | string – Part of the request URL that is after the question mark. |
queryStringWithoutPath | string – The request’s query string, without the path parameter. |
rawBody | string – The request body. |
rawCookies | yii\web\CookieCollection – The cookie collection. |
referrer | string, null – URL referrer, null if not available. |
remoteHost | string, null – Remote host name, null if not available. |
remoteIP | string, null – Remote IP address, null if not available. |
scriptFile | string – The entry script file path. |
scriptFilename | string – The requested script name being used to access Craft (e.g. “index.php”). |
scriptUrl | string – The relative URL of the entry script. |
secureHeaders | array – Lists of headers that are, by default, subject to the trusted host configuration. |
securePort | integer – Port number for secure requests. |
secureProtocolHeaders | array – List of headers to check for determining whether the connection is made via HTTPS. |
segments | array – The segments of the requested path. |
serverName | string, null – Server name, null if not available. |
serverPort | integer, null – Server port number, null if not available. |
siteToken | string, null – The token, or null if there isn’t one. |
sites | craft\services\Sites, array, string, null |
token | string – The token submitted with the request, if there is one. |
trustedHosts | array – The configuration for trusted security related headers. |
url | string – The currently requested relative URL. |
userAgent | string, null – User agent, null if not available. |
userHost | string, null – User host name, null if not available. |
userIP | string, null – User IP address, null if not available. |
_token
See also getToken()
acceptsImage
- Type
- boolean
- Default value
null
- Access
- Read-only
- Since
- 3.5.0
acceptsJson
- Type
- boolean
- Default value
null
- Access
- Read-only
actionSegments
- Type
- array
- Default value
null
The segments of the requested controller action path, if this is an action request.
bearerToken
clientOs
- Type
- string
- Default value
null
- Access
- Read-only
The OS the client is running.
fullPath
- Type
- string
- Default value
null
The full requested path, including the control panel trigger and pagination info.
fullUri
- Type
- string
- Default value
null
- Access
- Read-only
- Since
- 3.5.0
generalConfig
- Type
- craft\config\GeneralConfig, array, string
- Default value
null
- Since
- 3.5.10
hadToken
- Type
- boolean
- Default value
null
- Access
- Read-only
- Since
- 3.6.0
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.
isActionRequest
- Type
- boolean
- Default value
null
Whether a specific controller action was requested.
isCpRequest
- Type
- boolean
- Default value
null
Whether the control panel was requested.
isGraphql
- Type
- boolean
- Default value
null
Whether the request’s MIME type is application/graphql
isJson
- Type
- boolean
- Default value
null
Whether the request’s MIME type is application/json
isLivePreview
- Type
- boolean
- Default value
null
Whether this is a Live Preview request.
isLoginRequest
- Type
- boolean
- Default value
null
- Access
- Read-only
- Since
- 3.2.0
isPreview
- Type
- boolean
- Default value
null
Whether this is an element preview request.
isSiteRequest
- Type
- boolean
- Default value
null
Whether the front end site was requested.
maxPageNum
- Type
- integer
- Default value
100000
- Since
- 3.1.14
The highest page number that Craft should accept.
mimeType
The MIME type of the request, extracted from the request’s content type
normalizedContentType
pageNum
- Type
- integer
- Default value
null
The requested page number.
queryParamsWithoutPath
- Type
- array
- Default value
null
- Access
- Read-only
- Since
- 5.0.0
queryStringWithoutPath
- Type
- string
- Default value
null
The request’s query string, without the path parameter.
rawCookies
- Type
- yii\web\CookieCollection
- Default value
null
- Access
- Read-only
- Since
- 3.5.0
The cookie collection.
segments
- Type
- array
- Default value
null
The segments of the requested path.
siteToken
The token, or null
if there isn’t one.
sites
- Type
- craft\services\Sites, array, string, null
- Default value
'sites'
- Since
- 3.5.10
token
- Type
- string
- Default value
null
The token submitted with the request, if there is one.
Public Methods
Method | Description |
---|---|
__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. |
getBearerToken() | Returns the Bearer token value from the X-Craft-Authorization or Authorization header, if present. |
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). |
getIsSiteRequest() | Returns whether the front end site was requested. |
getIsWebRequest() | Returns whether this is a web request. |
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. |
getQueryParamsWithoutPath() | Returns the named GET parameters, without the path parameter. |
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
Arguments
$contentType
(string)
Returns
checkIfActionRequest()
- Since
- 3.7.0
Checks to see if this is an action request.
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
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.
Returns
string – The currently requested absolute URL.
getAcceptsImage()
- Since
- 3.5.0
Returns whether the request will accept an image response.
Returns
getAcceptsJson()
Returns whether the request will accept a JSON response.
Returns
getActionSegments()
Returns the segments of the requested controller action path, if this is an action request.
Returns
array, null – The action path segments, or null
if this isn’t an action request.
getBearerToken()
- Since
- 5.1.0
Returns the Bearer
token value from the X-Craft-Authorization
or Authorization
header, if present.
Returns
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:
Arguments
$name
(string) – 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');
{# 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.
Returns
array, object – The request parameters given in the request body.
Throws
- yii\base\InvalidConfigException
if a registered parser does not implement the\craft\web\RequestParserInterface
.
getClientOs()
Returns whether the client is running "Windows", "Mac", "Linux" or "Other", based on the browser's UserAgent string.
Returns
string – The OS the client is running.
Example
$clientOs = Craft::$app->request->clientOs;
{% 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.
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.
Returns
getFullUri()
- Since
- 3.5.0
Returns the full requested URI.
Returns
getHadToken()
- Since
- 3.6.0
Returns whether the request initially had a token.
Returns
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
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.
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
.
Returns
getIsJson()
- Since
- 3.5.0
Returns whether the request’s MIME type is application/json
.
Returns
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.
Returns
boolean – Whether this is a Live Preview request.
Example
$isLivePreview = Craft::$app->request->isLivePreview;
{% set isLivePreview = craft.app.request.isLivePreview %}
getIsLoginRequest()
- Since
- 3.2.0
Returns whether this was a Login request.
Returns
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().
Returns
Example
$isPreviewRequest = Craft::$app->request->isPreview;
{% set isPreviewRequest = craft.app.request.isPreview %}
getIsSiteRequest()
Returns whether the front end site was requested.
The result will always just be the opposite of whatever getIsCpRequest() returns.
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.
Returns
getNormalizedContentType()
- Since
- 3.3.8
Returns the normalized content type.
Returns
getPageNum()
Returns the requested page number.
Returns
integer – The requested page number.
Example
$page = Craft::$app->request->pageNum;
{% 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:
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.
Arguments
$returnRealPathInfo
(boolean) – Whether the real path info should be returned instead.
Returns
string – The requested path, or the path info.
Throws
- yii\base\InvalidConfigException
if the path info cannot be determined due to unexpected server configuration
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
) – The default parameter value if the GET parameter does not exist.
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');
{# 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.
Returns
array – The request GET parameter values.
getQueryParamsWithoutPath()
- Since
- 5.0.0
Returns the named GET parameters, without the path parameter.
Returns
getQueryStringWithoutPath()
Returns the request’s query string, without the path parameter.
Returns
string – The query string.
Example
$queryString = Craft::$app->request->queryStringWithoutPath;
{% 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.
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.
Arguments
$filterOptions
(integer) – Bitwise disjunction of flags that should be passed to filter_var() when validating the IP address. Options includeFILTER_FLAG_IPV4
,FILTER_FLAG_IPV6
,FILTER_FLAG_NO_PRIV_RANGE
, andFILTER_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
- yii\web\BadRequestHttpException
if the request does not have the body param
Example
// get required $_POST['foo']
$foo = Craft::$app->request->getRequiredBodyParam('foo');
// get required $_POST['foo']['bar']
$bar = Craft::$app->request->getRequiredBodyParam('foo.bar');
{# 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:
Arguments
$name
(string) – The parameter name.
Returns
mixed
– The parameter value.
Throws
- yii\web\BadRequestHttpException
if the request does not have the param
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
- yii\web\BadRequestHttpException
if the request does not have the query param
Example
// get required $_GET['foo']
$foo = Craft::$app->request->getRequiredQueryParam('foo');
// get required $_GET['foo']['bar']
$bar = Craft::$app->request->getRequiredQueryParam('foo.bar');
{# 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.
Arguments
$num
(integer) – Which segment to return (1-indexed).
Returns
string, null – The matching segment, or null
if there wasn’t one.
Example
$firstSegment = Craft::$app->request->getSegment(1);
{% 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.
Returns
array – The Craft path’s segments.
Example
$segments = Craft::$app->request->segments;
{% 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 config5:siteToken config setting (siteToken
by default), or an X-Craft-Site-Token
HTTP header on the request.
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 config5:tokenParam config setting (token
by default), or an X-Craft-Token
HTTP header on the request.
See also:
Returns
string, null – The token, or null
if there isn’t one.
Throws
- yii\web\BadRequestHttpException
if an invalid token is supplied
getUserIP()
Returns the user IP address.
The IP is determined using headers and / or $_SERVER
variables.
Arguments
$filterOptions
(integer) – Bitwise disjunction of flags that should be passed to filter_var() when validating the IP address. Options includeFILTER_FLAG_IPV4
,FILTER_FLAG_IPV6
,FILTER_FLAG_NO_PRIV_RANGE
, andFILTER_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
string, null – The parameter value
Throws
- yii\web\BadRequestHttpException
if the param value doesn’t pass validation
Example
// get validated $_POST['foo']
$foo = Craft::$app->request->getValidatedBodyParam('foo');
// get validated $_POST['foo']['bar']
$bar = Craft::$app->request->getValidatedBodyParam('foo.bar');
{# 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
- 4.4.6
Returns whether the request has a valid site token.
Returns
init()
Initializes the object.
This method is invoked at the end of the constructor after the object is initialized with the given configuration.
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.
Arguments
$detectTablets
(boolean) – Whether tablets should be considered “mobile”.
Returns
boolean – Whether the request is coming from a mobile browser.
Example
$isMobileBrowser = Craft::$app->request->isMobileBrowser();
{% set isMobileBrowser = craft.app.request.isMobileBrowser() %}
regenCsrfToken()
Regenerates a CSRF token.
setBodyParams()
Sets the request body parameters.
Arguments
setIsActionRequest()
- Since
- 3.7.8
Overrides whether this request should be treated as an action request.
See also checkIfActionRequest()View source
Arguments
$isActionRequest
(boolean)
setIsCpRequest()
- Since
- 3.5.0
Sets whether the control panel was requested.
Arguments
setIsLivePreview()
Sets whether this is a Live Preview request.
Arguments
$isLivePreview
(boolean)
setToken()
- Since
- 3.6.0
Sets the token value.
Arguments
Protected Methods
Method | Description |
---|---|
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
Arguments
$token
(string)
Returns
generateCsrfToken()
Generates an unmasked random token used to perform CSRF validation.
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.
Returns
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. |