Response
- Type
- Class
- Namespace
- craft\web
- Inherits
- craft\web\Response » yii\web\Response » yii\base\Response » yii\base\Component » yii\base\BaseObject
- Implements
- yii\base\Configurable
- Since
- 3.0.0
Public Properties
Property | Description |
---|---|
acceptMimeType | string – The MIME type (e.g. application/json ) from the request ACCEPT header chosen for this response. |
acceptParams | array – The parameters (e.g. ['q' => 1, 'version' => '1.0'] ) associated with the chosen MIME type. |
behaviors | yii\base\Behavior – List of behaviors attached to this component. |
charset | string, null – The charset of the text response. |
content | string, null – The response content. |
contentType | string, null |
cookies | yii\web\CookieCollection – The cookie collection. |
data | mixed – The original response data. |
defaultFormatters | – Default response formatter configurations. |
downloadHeaders | string – The attachment file name. |
exitStatus | integer – The exit status. |
format | string – The response format. |
formatters | array – The formatters for converting data into the response content of the specified format. |
headers | yii\web\HeaderCollection – The header collection. |
httpStatuses | array – List of HTTP status codes and the corresponding texts |
isClientError | boolean – Whether this response indicates a client error. |
isEmpty | boolean – Whether this response is empty. |
isForbidden | boolean – Whether this response indicates the current request is forbidden. |
isInformational | boolean – Whether this response is informational. |
isInvalid | boolean – Whether this response has a valid statusCode. |
isNotFound | boolean – Whether this response indicates the currently requested resource is not found. |
isOk | boolean – Whether this response is OK. |
isRedirection | boolean – Whether this response is a redirection. |
isSent | boolean – Whether the response has been sent. |
isServerError | boolean – Whether this response indicates a server error. |
isSuccessful | boolean – Whether this response is successful. |
lastModifiedHeader | string – The file to read the last modified date from. |
rawCookies | yii\web\CookieCollection – The cookie collection. |
statusCode | integer – The HTTP status code to send with the response. |
statusCodeByException | Throwable – The exception object. |
statusText | string – The HTTP status description that comes together with the status code. |
stream | resource, array, callable – The stream to be sent. |
version | string, null – The version of the HTTP protocol to use. |
contentType
defaultFormatters
- Default value
[]
- Since
- 4.5.0
This could be set from config/app.web.php
to append additional default response formatters, or modify existing ones.
use craft\helpers\App;
use craft\helpers\ArrayHelper;
use craft\web\Response;
return [
'components' => [
'response' => fn() => Craft::createObject(ArrayHelper::merge(
App::webResponseConfig(),
[
'defaultFormatters' => [
Response::FORMAT_CSV => [
'delimiter' => chr(9),
],
],
]
)),
],
];
See also defaultFormatters()
lastModifiedHeader
- Type
- string
- Default value
null
- Access
- Write-only
The file to read the last modified date from.
rawCookies
- Type
- yii\web\CookieCollection
- Default value
null
- Access
- Read-only
- Since
- 3.5.0
The cookie collection.
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. |
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. |
clear() | Clears the headers, cookies, content, status code of the response. |
clearOutputBuffers() | Removes all existing output buffers. |
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. |
getBehavior() | Returns the named behavior object. |
getBehaviors() | Returns all behaviors attached to this component. |
getContentType() | Returns the Content-Type header (sans charset=X ) that the response will most likely include. |
getCookies() | Returns the cookie collection. |
getHeaders() | Returns the header collection. |
getIsClientError() | |
getIsEmpty() | |
getIsForbidden() | |
getIsInformational() | |
getIsInvalid() | |
getIsNotFound() | |
getIsOk() | |
getIsRedirection() | |
getIsServerError() | |
getIsSuccessful() | |
getRawCookies() | Returns the “raw” cookie collection. |
getStatusCode() | |
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. |
init() | Initializes this component. |
off() | Detaches an existing event handler from this component. |
on() | Attaches an event handler to an event. |
redirect() | Redirects the browser to the specified URL. |
refresh() | Refreshes the current page. |
send() | Sends the response to the client. |
sendAndClose() | Attempts to closes the connection with the HTTP client, without ending PHP script execution. |
sendContentAsFile() | Sends the specified content as a file to the browser. |
sendFile() | Sends a file to the browser. |
sendStreamAsFile() | Sends the specified stream as a file to the browser. |
setCacheHeaders() | Sets headers that will instruct the client to cache this response. |
setDownloadHeaders() | Sets a default set of HTTP headers for file downloading purpose. |
setLastModifiedHeader() | Sets a Last-Modified header based on a given file path. |
setNoCacheHeaders() | Sets headers that will instruct the client to not cache this response. |
setStatusCode() | Sets the response status code. |
setStatusCodeByException() | Sets the response status code based on the exception. |
trigger() | Triggers an event. |
xSendFile() | Sends existing file to a browser as a download using x-sendfile. |
getContentType()
Returns the Content-Type header (sans charset=X
) that the response will most likely include.
Returns
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.
redirect()
Redirects the browser to the specified URL.
This method adds a "Location" header to the current response. Note that it does not send out the header until send() is called. In a controller action you may use this method as follows:
return Yii::$app->getResponse()->redirect($url);
In other places, if you want to send out the "Location" header immediately, you should use the following code:
Yii::$app->getResponse()->redirect($url)->send();
return;
In AJAX mode, this normally will not work as expected unless there are some client-side JavaScript code handling the redirection. To help achieve this goal, this method will send out a "X-Redirect" header instead of "Location".
If you use the "yii" JavaScript module, it will handle the AJAX redirection as described above. Otherwise, you should write the following JavaScript code to handle the redirection:
$document.ajaxComplete(function (event, xhr, settings) {
var url = xhr && xhr.getResponseHeader('X-Redirect');
if (url) {
window.location = url;
}
});
Arguments
$url
(string, array) – The URL to be redirected to. This can be in one of the following formats:a string representing a URL (e.g. "https://example.com")
a string representing a URL alias (e.g. "@example.com")
an array in the format of
[$route, ...name-value pairs...]
(e.g.['site/index', 'ref' => 1]
). Note that the route is with respect to the whole application, instead of relative to a controller or module. yii\helpers\Url::to() will be used to convert the array into a URL.
Any relative URL that starts with a single forward slash "/" will be converted into an absolute one by prepending it with the host info of the current request.
$statusCode
(integer) – The HTTP status code. Defaults to 302. See https://tools.ietf.org/html/rfc2616#section-10 for details about HTTP status code$checkAjax
(boolean) – Whether to specially handle AJAX (and PJAX) requests. Defaults to true, meaning if the current request is an AJAX or PJAX request, then calling this method will cause the browser to redirect to the given URL. If this is false, aLocation
header will be sent, which when received as an AJAX/PJAX response, may NOT cause browser redirection. Takes effect only when request headerX-Ie-Redirect-Compatibility
is absent.
Returns
$this – The response object itself
sendAndClose()
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/141026View source
Throws
- Throwable
An exception will be thrown if content has already been output.
sendContentAsFile()
Sends the specified content as a file to the browser.
Note that this method only prepares the response for file sending. The file is not sent until send() is called explicitly or implicitly. The latter is done after you return from a controller action.
\yii\web\Response::sendContentAsFile()
Arguments
$content
(string) – The content to be sent. The existing content will be discarded.$attachmentName
(string) – The file name shown to the user.$options
(array) – Additional options for sending the file. The following options are supported:mimeType
: the MIME type of the content. Defaults to 'application/octet-stream'.inline
: boolean, whether the browser should open the file within the browser window. Defaults to false, meaning a download dialog will pop up.
Returns
self
– Self reference
Throws
sendFile()
Sends a file to the browser.
Note that this method only prepares the response for file sending. The file is not sent until send() is called explicitly or implicitly. The latter is done after you return from a controller action.
The following is an example implementation of a controller action that allows requesting files from a directory that is not accessible from web:
public function actionFile($filename)
{
$storagePath = Yii::getAlias('@app/files');
// check filename for allowed chars (do not allow ../ to avoid security issue: downloading arbitrary files)
if (!preg_match('/^[a-z0-9]+\.[a-z0-9]+$/i', $filename) || !is_file("$storagePath/$filename")) {
throw new \yii\web\NotFoundHttpException('The file does not exists.');
}
return Yii::$app->response->sendFile("$storagePath/$filename", $filename);
}
\yii\web\Response::sendFile()
Arguments
$filePath
(string) – The path of the file to be sent.$attachmentName
(string, null) – The file name shown to the user. If null, it will be determined from$filePath
.$options
(array) – Additional options for sending the file. The following options are supported:mimeType
: the MIME type of the content. If not set, it will be guessed based on$filePath
inline
: boolean, whether the browser should open the file within the browser window. Defaults to false, meaning a download dialog will pop up.
Returns
self
– Self reference
setCacheHeaders()
Sets headers that will instruct the client to cache this response.
Arguments
$duration
(integer) – The total cache duration, in seconds. Defaults to 1 year.$overwrite
(boolean) – Whether the headers should overwrite existing headers, if already set
Returns
self
– Self reference
setLastModifiedHeader()
Sets a Last-Modified header based on a given file path.
Arguments
$path
(string) – The file to read the last modified date from.
Returns
self
– Self reference
setNoCacheHeaders()
- Since
- 3.5.0
Sets headers that will instruct the client to not cache this response.
Arguments
$overwrite
(boolean) – Whether the headers should overwrite existing headers, if already set
Returns
self
– Self reference
Protected Methods
Method | Description |
---|---|
defaultFormatters() | |
getDispositionHeaderValue() | Returns Content-Disposition header value that is safe to use with both old and new browsers. |
getHttpRange() | Determines the HTTP range given in the request. |
prepare() | Prepares for sending the response. |
sendContent() | Sends the response content to the client. |
sendCookies() | Sends the cookies to the client. |
sendHeaders() | Sends the response headers to the client. |
defaultFormatters()
- Since
- 3.4.0
Returns
array – The formatters that are supported by default
prepare()
Prepares for sending the response.
The default implementation will convert data into content and set headers accordingly.
Throws
- yii\base\InvalidConfigException
if the formatter for the specified format is invalid or format is not supported
sendCookies()
- Since
- 3.5.0
Sends the cookies to the client.
Constants
Constant | Description |
---|---|
FORMAT_CSV | |
FORMAT_HTML | |
FORMAT_JSON | |
FORMAT_JSONP | |
FORMAT_RAW | |
FORMAT_XML |