Request

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

View source

Public Properties

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

$acceptsJson

Type
boolean
Access
Read-only

View source

Signature

public boolean getAcceptsJson ( )

$actionSegments

Type
array, null
Access
Read-only

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

View source

Signature

public array, null getActionSegments ( )

$bodyParams

Type
array

The request parameters given in the request body.

View source

Signature

public array getBodyParams ( )
public void setBodyParams ( $values )

$clientOs

Type
string
Access
Read-only

The OS the client is running.

View source

Signature

public string getClientOs ( )

$csrfToken

Type
string
Access
Read-only

The token used to perform CSRF validation.

View source

Signature

public string getCsrfToken ( $regenerate = false )

$fullPath

Type
string
Access
Read-only

View source

Signature

public string getFullPath ( )

$ipHeaders

Type
string[]

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

View source

Signature

public string[] $ipHeaders = ['Client-IP', 'X-Forwarded-For', 'X-Forwarded', 'X-Cluster-Client-IP', 'Forwarded-For', 'Forwarded']

$isActionRequest

Type
boolean
Access
Read-only

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

View source

Signature

public boolean getIsActionRequest ( )

$isCpRequest

Type
boolean
Access
Read-only

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

View source

Signature

public boolean getIsCpRequest ( )

$isLivePreview

Type
boolean
Access
Read-only

Whether this is a Live Preview request.

View source

Signature

public boolean getIsLivePreview ( )

$isSingleActionRequest

Type

:

Access
Read-only

View source

Signature

public void getIsSingleActionRequest ( )

$isSiteRequest

Type
boolean
Access
Read-only

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

View source

Signature

public boolean getIsSiteRequest ( )

$pageNum

Type
integer
Access
Read-only

The requested page number.

View source

Signature

public integer getPageNum ( )

$pathInfo

Type
string

The requested path, or the path info.

View source

Signature

public string getPathInfo ( \craft\web\bool $returnRealPathInfo = false )
public void setPathInfo ( $value )

$queryParams

Type
array

The request GET parameter values.

View source

Signature

public array getQueryParams ( )
public void setQueryParams ( $values )

$queryStringWithoutPath

Type
string
Access
Read-only

The query string.

View source

Signature

public string getQueryStringWithoutPath ( )

$remoteIP

Type
string, null
Access
Read-only

Remote IP address, null if not available.

View source

Signature

public string, null getRemoteIP ( \craft\web\int $filterOptions = 0 )

$segments

Type
array
Access
Read-only

The Craft path’s segments.

View source

Signature

public array getSegments ( )

$token

Type
string, null
Access
Read-only

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

View source

Signature

public string, null getToken ( )

$userIP

Type
string, null
Access
Read-only

User IP address, null if not available

View source

Signature

public string, null getUserIP ( \craft\web\int $filterOptions = 0 )

Public Methods

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

accepts()

Returns whether the request will accept a given content type3

View source

Arguments

Returns

boolean

Signature

public boolean accepts ( \craft\web\string $contentType )

getAcceptsJson()

Returns whether the request will accept a JSON response.

View source

Returns

boolean

Signature

public boolean getAcceptsJson ( )

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.

Signature

public array, null getActionSegments ( )

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

Signature

public mixed getBodyParam ( $name, $defaultValue = null )

Example

getBodyParams()

Returns the request parameters given in the request body.

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

View source

Returns

array – The request parameters given in the request body.

Throws

Signature

public array getBodyParams ( )

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.

Signature

public string getClientOs ( )

Example

getCsrfToken()

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

View source

Arguments

  • $regenerate (boolean) – Whether to regenerate CSRF token. When this parameter is true, each time this method is called, a new CSRF token will be generated and persisted (in session or cookie).

Returns

string – The token used to perform CSRF validation.

Signature

public string getCsrfToken ( $regenerate = false )

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

Signature

public string getFullPath ( )

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.

Signature

public boolean getIsActionRequest ( )

getIsCpRequest()

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

View source

Returns

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

Signature

public boolean getIsCpRequest ( )

getIsLivePreview()

Returns whether this is a Live Preview request.

View source

Returns

boolean – Whether this is a Live Preview request.

Signature

public boolean getIsLivePreview ( )

Example

getIsSingleActionRequest()

Returns whether the current request is solely an action request.

View source

Signature

public void getIsSingleActionRequest ( )

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.

Signature

public boolean getIsSiteRequest ( )

getPageNum()

Returns the requested page number.

View source

Returns

integer – The requested page number.

Signature

public integer getPageNum ( )

Example

getParam()

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

View source

Arguments

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

Returns

mixed – The parameter value.

Signature

public mixed getParam ( \craft\web\string $name, $defaultValue = null )

getPathInfo()

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

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

View source

Arguments

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

Returns

string – The requested path, or the path info.

Throws

Signature

public string getPathInfo ( \craft\web\bool $returnRealPathInfo = false )

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.

Signature

public mixed getQueryParam ( $name, $defaultValue = null )

Example

getQueryParams()

Returns the request parameters given in the $queryString.

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

View source

Returns

array – The request GET parameter values.

Signature

public array getQueryParams ( )

getQueryStringWithoutPath()

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

View source

Returns

string – The query string.

Signature

public string getQueryStringWithoutPath ( )

Example

getRemoteIP()

Returns the IP on the other end of this connection.

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

View source

Arguments

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

Returns

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

Signature

public string, null getRemoteIP ( \craft\web\int $filterOptions = 0 )

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

Signature

public mixed getRequiredBodyParam ( \craft\web\string $name )

Example

getRequiredParam()

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

See also:

View source

Arguments

  • $name (string) – The parameter name.

Returns

mixed – The parameter value.

Throws

Signature

public mixed getRequiredParam ( \craft\web\string $name )

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

Signature

public mixed getRequiredQueryParam ( \craft\web\string $name )

Example

getSegment()

Returns a specific segment from the Craft path.

View source

Arguments

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

Returns

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

Signature

public string, null getSegment ( \craft\web\int $num )

Example

getSegments()

Returns the segments of the requested path.

TIP

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

View source

Returns

array – The Craft path’s segments.

Signature

public array getSegments ( )

Example

getToken()

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

View source

Returns

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

Signature

public string, null getToken ( )

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

Signature

public string, null getUserIP ( \craft\web\int $filterOptions = 0 )

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

Signature

public mixed, null getValidatedBodyParam ( \craft\web\string $name )

Example

init()

Initializes the object.

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

View source

Signature

public void init ( )

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.

Signature

public boolean isMobileBrowser ( \craft\web\bool $detectTablets = false )

Example

regenCsrfToken()

Regenerates a CSRF token.

View source

Signature

public void regenCsrfToken ( )

resolve()

Resolves the current request into a route and the associated parameters.

View source

Returns

array – The first element is the route, and the second is the associated parameters.

Throws

Signature

public array resolve ( )

Protected Methods

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

csrfTokenValidForCurrentUser()

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

View source

Arguments

Returns

boolean

Signature

protected boolean csrfTokenValidForCurrentUser ( \craft\web\string $token )

generateCsrfToken()

Generates an unmasked random token used to perform CSRF validation.

View source

Returns

string – The random token for CSRF validation.

Signature

protected string generateCsrfToken ( )

Constants

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