HttpRequestService

Type
Class
Namespace
Craft
Inherits
Craft\HttpRequestService » CHttpRequest » CApplicationComponent » CComponent
Implements
IApplicationComponent
Since
1.0

HttpRequestService provides APIs for getting information about the current HTTP request.

An instance of HttpRequestService is globally accessible in Craft via {@link WebApp::request craft()->request}.

See also http://craftcms.com

View source

Public Properties

PropertyDescription
$behaviorsarray – The behaviors that should be attached to this component.
$csrfCookiearray – The property values (in name-value pairs) used to initialize the CSRF cookie.
$csrfTokenNamestring – The name of the token used to prevent CSRF.
$enableCookieValidationboolean – Whether cookies should be validated to ensure they are not tampered.
$enableCsrfValidationboolean – Whether to enable CSRF (Cross-Site Request Forgery) validation.
$jsonAsArrayboolean – Whether the parsing of JSON REST requests should return associative arrays for object data.

Public Methods

MethodDescription
__call()Calls the named method which is not a class method.
__get()Returns a property value, an event handler list or a behavior based on its name.
__isset()Checks if a property value is null.
__set()Sets value of a component property.
__unset()Sets a component property to be null.
asa()Returns the named behavior object.
attachBehavior()Attaches a behavior to this component.
attachBehaviors()Attaches a list of behaviors to the component.
attachEventHandler()Attaches an event handler to an event.
canGetProperty()Determines whether a property can be read.
canSetProperty()Determines whether a property can be set.
close()Attempts to closes the connection with the HTTP client, without ending PHP script execution.
compareAcceptTypes()Compare function for determining the preference of accepted MIME type array maps See {@link parseAcceptHeader()} for the format of $a and $b
decodePathInfo()Decodes the path info.
deleteCookie()Deletes a cookie by its name.
detachBehavior()Detaches a behavior from the component.
detachBehaviors()Detaches all behaviors from the component.
detachEventHandler()Detaches an existing event handler.
disableBehavior()Disables an attached behavior.
disableBehaviors()Disables all behaviors attached to this component.
enableBehavior()Enables an attached behavior.
enableBehaviors()Enables all behaviors attached to this component.
evaluateExpression()Evaluates a PHP expression or callback under the context of this component.
getAcceptTypes()Returns user browser accept types, null if not present.
getActionSegments()Returns an array of the action path segments, if this is an {@link isActionRequest() action request}.
getBaseUrl()Returns the relative URL for the application.
getBrowser()Returns information about the capabilities of user browser.
getBrowserLanguages()Returns a list of languages the user has selected in their browser’s settings, canonicalized using {@link LocaleData::getCanonicalID}.
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 {@link getRawBody()} or, in the case of the HEAD method, the media type that would have been sent had the request been a GET.
getCookie()Returns a cookie by its name.
getCookies()Returns the cookie collection. The result can be used like an associative array. Adding {@link HttpCookie} objects to the collection will send the cookies to the client; and removing the objects from the collection will delete those cookies on the client.
getCsrfToken()Gets the current CSRF token from the CSRF token cookie, (re)creating the cookie if it is missing or invalid.
getDelete()Returns the named DELETE parameter value.
getEventHandlers()Returns the list of attached event handlers for an event.
getHostInfo()Returns the schema and host part of the application URL.
getHostName()Returns the host name, without “http://” or “https://”.
getHttpVersion()Returns the version of the HTTP protocol used by client.
getIpAddress()Retrieves the best guess of the client’s actual IP address taking into account numerous HTTP proxy headers due to variations in how different ISPs handle IP addresses in headers between hops.
getIsAjaxRequest()Returns whether this is an AJAX (XMLHttpRequest) request.
getIsDeleteRequest()Returns whether this is a DELETE request.
getIsFlashRequest()Returns whether this is an Adobe Flash or Adobe Flex request.
getIsGetRequest()Returns whether this is a GET request.
getIsInitialized()Checks if this application component has been initialized.
getIsPatchRequest()Returns whether this is a PATCH request.
getIsPostRequest()Returns whether this is a POST request.
getIsPutRequest()Returns whether this is a PUT request.
getIsSecureConnection()Return if the request is sent via secure channel (https).
getMimeType()Returns the MIME type that is going to be included in the response via the Content-Type header.
getNormalizedPath()Returns the path Craft should use to route this request, including the CP trigger if it is in there.
getPageNum()Returns the current page number.
getParam()Returns a parameter from either the query string or POST data.
getPatch()Returns the named PATCH parameter value.
getPath()Returns the request’s Craft path.
getPathInfo()Returns the path info of the currently requested URL.
getPort()Returns the port to use for insecure requests.
getPost()Returns a POST parameter, or all of them.
getPreferredAcceptType()Returns the user preferred accept MIME type.
getPreferredAcceptTypes()Returns an array of user accepted MIME types in order of preference.
getPreferredLanguage()Returns the user-preferred language that should be used by this application.
getPreferredLanguages()Returns an array of user accepted languages in order of preference.
getPut()Returns the named PUT parameter value.
getQuery()Returns a query string parameter, or all of them.
getQueryString()Returns part of the request URL that is after the question mark.
getQueryStringWithoutPath()Returns the request’s query string, without the p= parameter.
getRawBody()Returns the raw HTTP request body.
getRequestType()Returns the request type, such as GET, POST, HEAD, PUT, PATCH, DELETE.
getRequestUri()Returns the request URI portion for the currently requested URL.
getRequiredParam()Returns a parameter from either the query string or POST data, or bails on the request with a 400 error if that parameter doesn’t exist anywhere.
getRequiredPost()Returns a POST parameter, or bails on the request with a 400 error if that parameter doesn’t exist.
getRequiredQuery()Returns a query string parameter, or bails on the request with a 400 error if that parameter doesn’t exist.
getRestParams()Returns request parameters. Typically PUT, PATCH or DELETE.
getScriptFile()Returns entry script file path.
getScriptName()Returns the script name 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 an array of the Craft path’s segments.
getServerName()Returns the server name.
getServerPort()Returns the server port number.
getToken()Returns the request’s token, if there is one.
getUrl()Returns the currently requested URL.
getUrlReferrer()Returns the URL referrer, null if not present
getUserAgent()Returns the user agent, null if not present.
getUserHost()Returns the user host name, null if it cannot be determined.
getUserHostAddress()Alias of {@link getIpAddress()}.
getValidatedPost()Returns a POST parameter. If the validateUnsafeRequestParams config setting has been set to true, and this is a front-end request, then the POST parameter’s value will be validated with {@link SecurityService::validateData()} before being returned, ensuring that the value had not been tampered with by the user.
hasEvent()Determines whether an event is defined.
hasEventHandler()Checks whether the named event has attached handlers.
hasProperty()Determines whether a property is defined.
init()Initializes the application component.
isActionRequest()Returns whether the current request should be routed to a specific controller action before normal request routing takes over.
isAjaxRequest()Alias of {@link getIsAjaxRequest()}.
isCpRequest()Returns whether the current request should be routed to the Control Panel.
isDeleteRequest()Alias of {@link getIsDeleteRequest()}.
isDeleteViaPostRequest()Alias of {@link getIsDeleteViaPostRequest()}.
isFlashRequest()Alias of {@link getIsFlashRequest()}.
isGetRequest()Alias of {@link getIsGetRequest()}.
isLivePreview()Returns whether this is a Live Preview request.
isMobileBrowser()Returns whether the request is coming from a mobile browser.
isPostRequest()Alias of {@link getIsPostRequest()}.
isPutRequest()Alias of {@link getIsPutRequest()}.
isPutViaPostRequest()Alias of {@link getIsPutViaPostRequest()}.
isResourceRequest()Returns whether the current request should be routed to a resource.
isSecureConnection()Alias of {@link getIsSecureConnection()}.
isSingleActionRequest()Returns whether the current request is solely an action request.
isSiteRequest()Returns whether the current request should be routed to the front-end site.
parseAcceptHeader()Parses an HTTP Accept header, returning an array map with all parts of each entry.
raiseEvent()Raises an event.
redirect()Redirects the browser to the specified URL.
regenCsrfCookie()
sendFile()Sends a file to the user.
setBaseUrl()Sets the relative URL for the application.
setHostInfo()Sets the schema and host part of the application URL.
setPort()Sets the port to use for insecure requests.
setScriptUrl()Sets the relative URL for the application entry script.
setSecurePort()Sets the port to use for secure requests.
stripSlashes()Strips slashes from input data.
validateCsrfToken()Performs the CSRF validation. This is the event handler responding to {@link CApplication::onBeginRequest}.
xSendFile()Sends existing file to a browser as a download using x-sendfile.

close()

Attempts to closes the connection with the HTTP client, without ending PHP script execution. This method relies on flush(), which may not actually work if mod_deflate or mod_gzip is installed, or if this is a Win32 server. See also http://stackoverflow.com/a/141026 View source

Arguments

  • $content (string, null) – Any content that should be included in the response body.

Returns

null

Throws

  • Craft\Exception
    An exception will be thrown if content has already been output.

Signature

public null close ( $content = '' )

decodePathInfo()

Decodes the path info. Replacement for Yii's {@link \CHttpRequest::decodePathInfo()}.

View source

Arguments

  • $pathInfo (string) – Encoded path info.

Returns

string – Decoded path info.

Signature

public string decodePathInfo ( $pathInfo )

deleteCookie()

Deletes a cookie by its name.

View source

Arguments

  • $name – The cookie name.

Returns

null

Signature

public null deleteCookie ( $name )

getActionSegments()

Returns an array of the action path segments, if this is an {@link isActionRequest() 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 ( )

getBrowserLanguages()

Returns a list of languages the user has selected in their browser’s settings, canonicalized using {@link LocaleData::getCanonicalID}. Internally, this method checks the Accept-Language header that should have accompanied the request. If that header was not present, the method will return false.

View source

Returns

array, false – The preferred languages, or false if Craft is unable to determine them.

Signature

public array, false getBrowserLanguages ( )

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 ( )

getCookie()

Returns a cookie by its name.

View source

Arguments

  • $name (string) – The cookie name.

Returns

Craft\HttpCookie, null – The cookie, or null if it didn’t exist.

Signature

public Craft\HttpCookie, null getCookie ( $name )

getCookies()

Returns the cookie collection. The result can be used like an associative array. Adding {@link HttpCookie} objects to the collection will send the cookies to the client; and removing the objects from the collection will delete those cookies on the client.

View source

Returns

Craft\CookieCollection – The cookie collection.

Signature

public Craft\CookieCollection getCookies ( )

getCsrfToken()

Gets the current CSRF token from the CSRF token cookie, (re)creating the cookie if it is missing or invalid.

View source

Returns

string

Throws

Signature

public string getCsrfToken ( )

getHostName()

Returns the host name, without “http://” or “https://”. Internally, this method will first check the Host header that should have accompanied the request, which browsers will set depending on the host name they are requesting. If that header does not exist, the method will fall back on the SERVER_NAME server environment variable.

View source

Returns

string – The host name.

Signature

public string getHostName ( )

getIpAddress()

Retrieves the best guess of the client’s actual IP address taking into account numerous HTTP proxy headers due to variations in how different ISPs handle IP addresses in headers between hops. Considering any of these server vars besides REMOTE_ADDR can be spoofed, this method should not be used when you need a trusted source for the IP address. Use $_SERVER['REMOTE_ADDR'] instead.

View source

Returns

string – The IP address.

Signature

public string getIpAddress ( )

getIsGetRequest()

Returns whether this is a GET request.

View source

Returns

boolean – Whether this is a GET request.

Signature

public boolean getIsGetRequest ( )

getMimeType()

DEPRECATED

Deprecated Deprecated in 2.2. Use {@link HeaderHelper::getMimeType()} instead.

Returns the MIME type that is going to be included in the response via the Content-Type header.

View source

Returns

string

Signature

public string getMimeType ( )

getNormalizedPath()

Returns the path Craft should use to route this request, including the CP trigger if it is in there.

View source

Returns

string – The path.

Signature

public string getNormalizedPath ( )

getPageNum()

Returns the current page number.

View source

Returns

integer – The page number.

Signature

public integer getPageNum ( )

getParam()

Returns a parameter from either the query string or POST data. This method will first search for the given paramater in the query string, calling {@link getQuery()} internally, and if that doesn’t come back with a value, it will call {@link getPost()}. If that doesn’t come back with a value either, $defaultValue will be returned.

$foo = craft()->request->getParam('foo'); // Returns $_GET['foo'] or $_POST['foo'], if either exist

$name can also represent a nested parameter using a dot-delimited string.

$bar = craft()->request->getParam('foo.bar'); // Returns $_GET['foo']['bar'] or $_POST['foo']['bar'], if either exist

All values will be converted to UTF-8, regardless of the original character encoding.

View source

Arguments

  • $name (string) – The dot-delimited name of the param to be fetched.
  • $defaultValue (mixed) – The fallback value to be returned if no param exists by the given $name. Defaults to null.

Returns

mixed – The value of the corresponding param, or $defaultValue if that value didn’t exist.

Signature

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

getPath()

Returns the request’s Craft path. Note that the path 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

string – The Craft path.

Signature

public string getPath ( )

getPost()

Returns a POST parameter, or all of them. If $name is specified, then the corresponding POST parameter will be returned if it exists, or $defaultValue will be returned if it doesn’t.

$foo = craft()->request->getPost('foo'); // Returns $_POST['foo'], if it exists

$name can also represent a nested parameter using a dot-delimited string.

$bar = craft()->request->getPost('foo.bar'); // Returns $_POST['foo']['bar'], if it exists

If $name is omitted, the entire $_POST array will be returned instead:

$allThePostParams = craft()->request->getPost(); // Returns $_POST

All values will be converted to UTF-8, regardless of the original character encoding.

View source

Arguments

  • $name (string, null) – The dot-delimited name of the POST param to be fetched, if any.
  • $defaultValue (mixed) – The fallback value to be returned if no param exists by the given $name. Defaults to null.

Returns

mixed – The value of the corresponding POST param if a single param was requested, or $defaultValue if that value didn’t exist, or the entire $_POST array if no single param was requested.

Signature

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

getQuery()

Returns a query string parameter, or all of them. If $name is specified, then the corresponding query string parameter will be returned if it exists, or $defaultValue will be returned if it doesn’t.

$foo = craft()->request->getQuery('foo'); // Returns $_GET['foo'], if it exists

$name can also represent a nested parameter using a dot-delimited string.

$bar = craft()->request->getQuery('foo.bar'); // Returns $_GET['foo']['bar'], if it exists

If $name is omitted, the entire $_GET array will be returned instead:

$allTheQueryParams = craft()->request->getQuery(); // Returns $_GET

All values will be converted to UTF-8, regardless of the original character encoding.

View source

Arguments

  • $name (string, null) – The dot-delimited name of the query string param to be fetched, if any.
  • $defaultValue (mixed) – The fallback value to be returned if no param exists by the given $name. Defaults to null.

Returns

mixed – The value of the corresponding query string param if a single param was requested, or $defaultValue if that value didn’t exist, or the entire $_GET array if no single param was requested.

Signature

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

getQueryStringWithoutPath()

Returns the request’s query string, without the p= parameter.

View source

Returns

string – The query string.

Signature

public string getQueryStringWithoutPath ( )

getRequiredParam()

Returns a parameter from either the query string or POST data, or bails on the request with a 400 error if that parameter doesn’t exist anywhere. This method will first search for the given paramater in the query string, calling {@link getQuery()} internally, and if that doesn’t come back with a value, it will call {@link getPost()}.

$foo = craft()->request->getRequiredParam('foo'); // Returns $_GET['foo'] or $_POST['foo']

$name can also represent a nested parameter using a dot-delimited string.

$bar = craft()->request->getParam('foo.bar'); // Returns $_GET['foo']['bar'] or $_POST['foo']['bar'], if either exist

All values will be converted to UTF-8, regardless of the original character encoding.

View source

Arguments

  • $name (string) – The dot-delimited name of the param to be fetched.

Returns

mixed – The value of the corresponding param, or $defaultValue if that value didn’t exist.

Throws

Signature

public mixed getRequiredParam ( $name )

getRequiredPost()

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

$foo = craft()->request->getRequiredPost('foo'); // Returns $_POST['foo']

$name can also represent a nested parameter using a dot-delimited string.

$bar = craft()->request->getRequiredPost('foo.bar'); // Returns $_POST['foo']['bar']

The returned value will be converted to UTF-8, regardless of the original character encoding.

View source

Arguments

  • $name (string) – The dot-delimited name of the POST param to be fetched.

Returns

mixed – The value of the corresponding POST param.

Throws

Signature

public mixed getRequiredPost ( $name )

getRequiredQuery()

Returns a query string parameter, or bails on the request with a 400 error if that parameter doesn’t exist.

$foo = craft()->request->getRequiredQuery('foo'); // Returns $_GET['foo']

$name can also represent a nested parameter using a dot-delimited string.

$bar = craft()->request->getRequiredQuery('foo.bar'); // Returns $_GET['foo']['bar']

The returned value will be converted to UTF-8, regardless of the original character encoding.

View source

Arguments

  • $name (string) – The dot-delimited name of the query string param to be fetched.

Returns

mixed – The value of the corresponding query string param.

Throws

Signature

public mixed getRequiredQuery ( $name )

getScriptName()

Returns the script name used to access Craft (e.g. “index.php”).

View source

Returns

string

Signature

public string getScriptName ( )

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 ( $num )

getSegments()

Returns an array of the Craft path’s segments. 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 ( )

getToken()

Returns the request’s token, if there is one.

View source

Returns

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

Signature

public string, null getToken ( )

getUserHostAddress()

Alias of {@link getIpAddress()}.

View source

Returns

string

Signature

public string getUserHostAddress ( )

getValidatedPost()

Returns a POST parameter. If the validateUnsafeRequestParams config setting has been set to true, and this is a front-end request, then the POST parameter’s value will be validated with {@link SecurityService::validateData()} before being returned, ensuring that the value had not been tampered with by the user.

View source

Arguments

  • $name (string) – The dot-delimited name of the POST param to be fetched.

Returns

mixed – The value of the corresponding POST param

Signature

public mixed getValidatedPost ( $name )

init()

Initializes the application component.

View source

Returns

null

Signature

public null init ( )

isActionRequest()

Returns whether the current request should be routed to a specific controller action before normal request routing takes over. 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 isActionRequest ( )

isAjaxRequest()

Alias of {@link getIsAjaxRequest()}.

View source

Returns

boolean

Signature

public boolean isAjaxRequest ( )

isCpRequest()

Returns whether the current request should be routed to the Control Panel. The result depends on whether the first segment in the URI matches the CP trigger.

Note that even if this function returns true, the request will not necessarily route to the Control Panel. It could instead route to a resource, for example.

View source

Returns

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

Signature

public boolean isCpRequest ( )

isDeleteRequest()

Alias of {@link getIsDeleteRequest()}.

View source

Returns

boolean

Signature

public boolean isDeleteRequest ( )

isDeleteViaPostRequest()

Alias of {@link getIsDeleteViaPostRequest()}.

View source

Returns

boolean

Signature

public boolean isDeleteViaPostRequest ( )

isFlashRequest()

Alias of {@link getIsFlashRequest()}.

View source

Returns

boolean

Signature

public boolean isFlashRequest ( )

isGetRequest()

Alias of {@link getIsGetRequest()}.

View source

Signature

public void isGetRequest ( )

isLivePreview()

Returns whether this is a Live Preview request.

View source

Returns

boolean – Whether this is a Live Preview request.

Signature

public boolean isLivePreview ( )

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 “modile”.

Returns

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

Signature

public boolean isMobileBrowser ( $detectTablets = false )

isPostRequest()

Alias of {@link getIsPostRequest()}.

View source

Returns

boolean

Signature

public boolean isPostRequest ( )

isPutRequest()

Alias of {@link getIsPutRequest()}.

View source

Returns

boolean

Signature

public boolean isPutRequest ( )

isPutViaPostRequest()

Alias of {@link getIsPutViaPostRequest()}.

View source

Returns

boolean

Signature

public boolean isPutViaPostRequest ( )

isResourceRequest()

Returns whether the current request should be routed to a resource. The result depends on whether the first segment in the Craft path matches the resource trigger.

View source

Returns

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

Signature

public boolean isResourceRequest ( )

isSecureConnection()

Alias of {@link getIsSecureConnection()}.

View source

Returns

boolean

Signature

public boolean isSecureConnection ( )

isSingleActionRequest()

Returns whether the current request is solely an action request.

View source

Signature

public void isSingleActionRequest ( )

isSiteRequest()

Returns whether the current request should be routed to the front-end site. The result will always just be the opposite of whatever {@link isCpRequest()} returns.

View source

Returns

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

Signature

public boolean isSiteRequest ( )

regenCsrfCookie()

Signature

public void regenCsrfCookie ( )

sendFile()

Sends a file to the user. We’re overriding this from {@link \CHttpRequest::sendFile()} so we can have more control over the headers.

View source

Arguments

  • $path (string) – The path to the file on the server.
  • $content (string) – The contents of the file.
  • $options (array, null) – An array of optional options. Possible keys include 'forceDownload', 'mimeType', and 'cache'.
  • $terminate (boolean, null) – Whether the request should be terminated after the file has been sent. Defaults to true.

Returns

null

Throws

Signature

public null sendFile ( $path, $content, $options = [], $terminate = true )

validateCsrfToken()

Performs the CSRF validation. This is the event handler responding to {@link CApplication::onBeginRequest}. The default implementation will compare the CSRF token obtained from session and from a POST field. If they are different, a CSRF attack is detected.

View source

Arguments

Throws

Signature

public void validateCsrfToken ( $event )

Protected Methods

MethodDescription
createCsrfCookie()Creates a cookie with a randomly generated CSRF token. Initial values specified in {@link csrfCookie} will be applied to the generated cookie.
csrfTokenValidForCurrentUser()Gets whether the CSRF token is valid for the current user or not
getIsDeleteViaPostRequest()Returns whether this is a DELETE request which was tunneled through POST.
getIsPatchViaPostRequest()Returns whether this is a PATCH request which was tunneled through POST.
getIsPutViaPostRequest()Returns whether this is a PUT request which was tunneled through POST.
normalizeRequest()Normalizes the request data.

createCsrfCookie()

Creates a cookie with a randomly generated CSRF token. Initial values specified in {@link csrfCookie} will be applied to the generated cookie.

View source

Returns

Craft\HttpCookie – The generated cookie

Signature

protected Craft\HttpCookie createCsrfCookie ( )

csrfTokenValidForCurrentUser()

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

View source

Arguments

  • $token

Returns

boolean

Throws

Signature

protected boolean csrfTokenValidForCurrentUser ( $token )