Class yii\web\Response
Inheritance | yii\web\Response » yii\base\Response » yii\base\Component » yii\base\BaseObject |
---|---|
Implements | yii\base\Configurable |
Available since version | 2.0 |
Source Code | https://github.com/yiisoft/yii2/blob/master/framework/web/Response.php |
The web Response class represents an HTTP response.
It holds the $headers, $cookies and $content that is to be sent to the client. It also controls the HTTP status code.
Response is configured as an application component in yii\web\Application by default.
You can access that instance via Yii::$app->response
.
You can modify its configuration by adding an array to your application config under components
as it is shown in the following example:
'response' => [
'format' => yii\web\Response::FORMAT_JSON,
'charset' => 'UTF-8',
// ...
]
For more details and usage information on Response, see the guide article on responses.
Public Properties
Property | Type | Description | Defined By |
---|---|---|---|
$acceptMimeType | string | The MIME type (e.g. application/json ) from the request ACCEPT header chosen for this response. |
yii\web\Response |
$acceptParams | array | The parameters (e.g. `['q' => 1, 'version' => '1. | yii\web\Response |
$behaviors | yii\base\Behavior[] | List of behaviors attached to this component | yii\base\Component |
$charset | string | The charset of the text response. | yii\web\Response |
$content | string | The response content. | yii\web\Response |
$cookies | yii\web\CookieCollection | The cookie collection. | yii\web\Response |
$data | mixed | The original response data. | yii\web\Response |
$downloadHeaders | string | The attachment file name | yii\web\Response |
$exitStatus | integer | The exit status. | yii\base\Response |
$format | string | The response format. | yii\web\Response |
$formatters | array | The formatters for converting data into the response content of the specified $format. | yii\web\Response |
$headers | yii\web\HeaderCollection | The header collection | yii\web\Response |
$httpStatuses | array | List of HTTP status codes and the corresponding texts | yii\web\Response |
$isClientError | boolean | Whether this response indicates a client error | yii\web\Response |
$isEmpty | boolean | Whether this response is empty | yii\web\Response |
$isForbidden | boolean | Whether this response indicates the current request is forbidden | yii\web\Response |
$isInformational | boolean | Whether this response is informational | yii\web\Response |
$isInvalid | boolean | Whether this response has a valid $statusCode. | yii\web\Response |
$isNotFound | boolean | Whether this response indicates the currently requested resource is not found | yii\web\Response |
$isOk | boolean | Whether this response is OK | yii\web\Response |
$isRedirection | boolean | Whether this response is a redirection | yii\web\Response |
$isSent | boolean | Whether the response has been sent. | yii\web\Response |
$isServerError | boolean | Whether this response indicates a server error | yii\web\Response |
$isSuccessful | boolean | Whether this response is successful | yii\web\Response |
$statusCode | integer | The HTTP status code to send with the response. | yii\web\Response |
$statusCodeByException | Exception|Error | The exception object. | yii\web\Response |
$statusText | string | The HTTP status description that comes together with the status code. | yii\web\Response |
$stream | resource|array | The stream to be sent. | yii\web\Response |
$version | string | The version of the HTTP protocol to use. | yii\web\Response |
Public Methods
Method | Description | Defined By |
---|---|---|
__call() | Calls the named method which is not a class method. | yii\base\Component |
__clone() | This method is called after the object is created by cloning an existing one. | yii\base\Component |
__construct() | Constructor. | yii\base\BaseObject |
__get() | Returns the value of a component property. | yii\base\Component |
__isset() | Checks if a property is set, i.e. defined and not null. | yii\base\Component |
__set() | Sets the value of a component property. | yii\base\Component |
__unset() | Sets a component property to be null. | yii\base\Component |
attachBehavior() | Attaches a behavior to this component. | yii\base\Component |
attachBehaviors() | Attaches a list of behaviors to the component. | yii\base\Component |
behaviors() | Returns a list of behaviors that this component should behave as. | yii\base\Component |
canGetProperty() | Returns a value indicating whether a property can be read. | yii\base\Component |
canSetProperty() | Returns a value indicating whether a property can be set. | yii\base\Component |
className() | Returns the fully qualified name of this class. | yii\base\BaseObject |
clear() | Clears the headers, cookies, content, status code of the response. | yii\web\Response |
clearOutputBuffers() | Removes all existing output buffers. | yii\base\Response |
detachBehavior() | Detaches a behavior from the component. | yii\base\Component |
detachBehaviors() | Detaches all behaviors from the component. | yii\base\Component |
ensureBehaviors() | Makes sure that the behaviors declared in behaviors() are attached to this component. | yii\base\Component |
getBehavior() | Returns the named behavior object. | yii\base\Component |
getBehaviors() | Returns all behaviors attached to this component. | yii\base\Component |
getCookies() | Returns the cookie collection. | yii\web\Response |
getHeaders() | Returns the header collection. | yii\web\Response |
getIsClientError() | yii\web\Response | |
getIsEmpty() | yii\web\Response | |
getIsForbidden() | yii\web\Response | |
getIsInformational() | yii\web\Response | |
getIsInvalid() | yii\web\Response | |
getIsNotFound() | yii\web\Response | |
getIsOk() | yii\web\Response | |
getIsRedirection() | yii\web\Response | |
getIsServerError() | yii\web\Response | |
getIsSuccessful() | yii\web\Response | |
getStatusCode() | yii\web\Response | |
hasEventHandlers() | Returns a value indicating whether there is any handler attached to the named event. | yii\base\Component |
hasMethod() | Returns a value indicating whether a method is defined. | yii\base\Component |
hasProperty() | Returns a value indicating whether a property is defined for this component. | yii\base\Component |
init() | Initializes this component. | yii\web\Response |
off() | Detaches an existing event handler from this component. | yii\base\Component |
on() | Attaches an event handler to an event. | yii\base\Component |
redirect() | Redirects the browser to the specified URL. | yii\web\Response |
refresh() | Refreshes the current page. | yii\web\Response |
send() | Sends the response to the client. | yii\web\Response |
sendContentAsFile() | Sends the specified content as a file to the browser. | yii\web\Response |
sendFile() | Sends a file to the browser. | yii\web\Response |
sendStreamAsFile() | Sends the specified stream as a file to the browser. | yii\web\Response |
setDownloadHeaders() | Sets a default set of HTTP headers for file downloading purpose. | yii\web\Response |
setStatusCode() | Sets the response status code. | yii\web\Response |
setStatusCodeByException() | Sets the response status code based on the exception. | yii\web\Response |
trigger() | Triggers an event. | yii\base\Component |
xSendFile() | Sends existing file to a browser as a download using x-sendfile. | yii\web\Response |
Protected Methods
Method | Description | Defined By |
---|---|---|
defaultFormatters() | yii\web\Response | |
getDispositionHeaderValue() | Returns Content-Disposition header value that is safe to use with both old and new browsers. | yii\web\Response |
getHttpRange() | Determines the HTTP range given in the request. | yii\web\Response |
prepare() | Prepares for sending the response. | yii\web\Response |
sendContent() | Sends the response content to the client. | yii\web\Response |
sendCookies() | Sends the cookies to the client. | yii\web\Response |
sendHeaders() | Sends the response headers to the client. | yii\web\Response |
Events
Event | Type | Description | Defined By |
---|---|---|---|
EVENT_AFTER_PREPARE | \yii\web\ResponseEvent | An event that is triggered right after prepare() is called in send(). | yii\web\Response |
EVENT_AFTER_SEND | \yii\web\ResponseEvent | An event that is triggered at the end of send(). | yii\web\Response |
EVENT_BEFORE_SEND | \yii\web\ResponseEvent | An event that is triggered at the beginning of send(). | yii\web\Response |
Constants
Constant | Value | Description | Defined By |
---|---|---|---|
FORMAT_HTML | 'html' | yii\web\Response | |
FORMAT_JSON | 'json' | yii\web\Response | |
FORMAT_JSONP | 'jsonp' | yii\web\Response | |
FORMAT_RAW | 'raw' | yii\web\Response | |
FORMAT_XML | 'xml' | yii\web\Response |
Property Details
The MIME type (e.g. application/json
) from the request ACCEPT header chosen for this response.
This property is mainly set by yii\filters\ContentNegotiator.
The parameters (e.g. ['q' => 1, 'version' => '1.0']
) associated with the chosen MIME type.
This is a list of name-value pairs associated with $acceptMimeType from the ACCEPT HTTP header.
This property is mainly set by yii\filters\ContentNegotiator.
The charset of the text response. If not set, it will use the value of yii\web\Application::$charset.
The response content. When $data is not null, it will be converted into $content according to $format when the response is being sent out.
See also $data.
The cookie collection.
The original response data. When this is not null, it will be converted into $content according to $format when the response is being sent out.
See also $content.
The attachment file name
The response format. This determines how to convert $data into $content when the latter is not set. The value of this property must be one of the keys declared in the $formatters array. By default, the following formats are supported:
- FORMAT_RAW: the data will be treated as the response content without any conversion. No extra HTTP header will be added.
- FORMAT_HTML: the data will be treated as the response content without any conversion. The "Content-Type" header will set as "text/html".
- FORMAT_JSON: the data will be converted into JSON format, and the "Content-Type" header will be set as "application/json".
- FORMAT_JSONP: the data will be converted into JSONP format, and the "Content-Type"
header will be set as "text/javascript". Note that in this case
$data
must be an array with "data" and "callback" elements. The former refers to the actual data to be sent, while the latter refers to the name of the JavaScript callback. - FORMAT_XML: the data will be converted into XML format. Please refer to yii\web\XmlResponseFormatter for more details.
You may customize the formatting process or support additional formats by configuring $formatters.
See also $formatters.
The formatters for converting data into the response content of the specified $format. The array keys are the format names, and the array values are the corresponding configurations for creating the formatter objects.
See also:
The header collection
List of HTTP status codes and the corresponding texts
Whether this response indicates a client error
Whether this response is empty
Whether this response indicates the current request is forbidden
Whether this response is informational
Whether this response has a valid $statusCode.
Whether this response indicates the currently requested resource is not found
Whether this response is OK
Whether this response is a redirection
Whether the response has been sent. If this is true, calling send() will do nothing.
Whether this response indicates a server error
Whether this response is successful
The HTTP status code to send with the response.
The exception object.
The HTTP status description that comes together with the status code.
See also $httpStatuses.
The stream to be sent. This can be a stream handle or an array of stream handle, the begin position and the end position. Note that when this property is set, the $data and $content properties will be ignored by send().
The version of the HTTP protocol to use. If not set, it will be determined via $_SERVER['SERVER_PROTOCOL']
,
or '1.1' if that is not available.
Method Details
Clears the headers, cookies, content, status code of the response.
public void clear ( ) |
protected array defaultFormatters ( ) | ||
return | array | The formatters that are supported by default |
---|
Returns the cookie collection.
Through the returned cookie collection, you add or remove cookies as follows,
// add a cookie
$response->cookies->add(new Cookie([
'name' => $name,
'value' => $value,
]);
// remove a cookie
$response->cookies->remove('name');
// alternatively
unset($response->cookies['name']);
public yii\web\CookieCollection getCookies ( ) | ||
return | yii\web\CookieCollection | The cookie collection. |
---|
Returns Content-Disposition header value that is safe to use with both old and new browsers.
Fallback name:
- Causes issues if contains non-ASCII characters with codes less than 32 or more than 126.
- Causes issues if contains urlencoded characters (starting with
%
) or%
character. Some browsers interpretfilename="X"
as urlencoded name, some don't. - Causes issues if contains path separator characters such as
\
or/
. - Since value is wrapped with
"
, it should be escaped as\"
. - Since input could contain non-ASCII characters, fallback is obtained by transliteration.
UTF name:
- Causes issues if contains path separator characters such as
\
or/
. - Should be urlencoded since headers are ASCII-only.
- Could be omitted if it exactly matches fallback name.
protected string getDispositionHeaderValue ( $disposition, $attachmentName ) | ||
$disposition | string | |
$attachmentName | string |
Returns the header collection.
The header collection contains the currently registered HTTP headers.
public yii\web\HeaderCollection getHeaders ( ) | ||
return | yii\web\HeaderCollection | The header collection |
---|
Determines the HTTP range given in the request.
protected array|boolean getHttpRange ( $fileSize ) | ||
$fileSize | integer | The size of the file that will be used to validate the requested HTTP range. |
return | array|boolean | The range (begin, end), or false if the range request is invalid. |
---|
public boolean getIsClientError ( ) | ||
return | boolean | Whether this response indicates a client error |
---|
public boolean getIsEmpty ( ) | ||
return | boolean | Whether this response is empty |
---|
public boolean getIsForbidden ( ) | ||
return | boolean | Whether this response indicates the current request is forbidden |
---|
public boolean getIsInformational ( ) | ||
return | boolean | Whether this response is informational |
---|
public boolean getIsInvalid ( ) | ||
return | boolean | Whether this response has a valid $statusCode. |
---|
public boolean getIsNotFound ( ) | ||
return | boolean | Whether this response indicates the currently requested resource is not found |
---|
public boolean getIsOk ( ) | ||
return | boolean | Whether this response is OK |
---|
public boolean getIsRedirection ( ) | ||
return | boolean | Whether this response is a redirection |
---|
public boolean getIsServerError ( ) | ||
return | boolean | Whether this response indicates a server error |
---|
public boolean getIsSuccessful ( ) | ||
return | boolean | Whether this response is successful |
---|
public integer getStatusCode ( ) | ||
return | integer | The HTTP status code to send with the response. |
---|
Initializes this component.
public void init ( ) |
Prepares for sending the response.
The default implementation will convert $data into $content and set headers accordingly.
protected void prepare ( ) | ||
throws | yii\base\InvalidConfigException | if the formatter for the specified format is invalid or $format is not supported |
---|
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;
}
});
public $this redirect ( $url, $statusCode = 302, $checkAjax = true ) | ||
$url | string|array | The URL to be redirected to. This can be in one of the following formats:
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, a |
return | $this | The response object itself |
---|
Refreshes the current page.
The effect of this method call is the same as the user pressing the refresh button of his browser (without re-posting data).
In a controller action you may use this method like this:
return Yii::$app->getResponse()->refresh();
public yii\web\Response refresh ( $anchor = '' ) | ||
$anchor | string | The anchor that should be appended to the redirection URL. Defaults to empty. Make sure the anchor starts with '#' if you want to specify it. |
return | yii\web\Response | The response object itself |
---|
Sends the response to the client.
public void send ( ) |
Sends the response content to the client.
protected void sendContent ( ) |
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.
See also sendFile() for an example implementation.
public $this sendContentAsFile ( $content, $attachmentName, $options = [] ) | ||
$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:
|
return | $this | The response object itself |
---|---|---|
throws | yii\web\RangeNotSatisfiableHttpException | if the requested range is not satisfiable |
Sends the cookies to the client.
protected void sendCookies ( ) |
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);
}
See also:
public $this sendFile ( $filePath, $attachmentName = null, $options = [] ) | ||
$filePath | string | The path of the file to be sent. |
$attachmentName | string | The file name shown to the user. If null, it will be determined from |
$options | array | Additional options for sending the file. The following options are supported:
|
return | $this | The response object itself |
---|
Sends the response headers to the client.
protected void sendHeaders ( ) |
Sends the specified stream 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.
See also sendFile() for an example implementation.
public $this sendStreamAsFile ( $handle, $attachmentName, $options = [] ) | ||
$handle | resource | The handle of the stream to be sent. |
$attachmentName | string | The file name shown to the user. |
$options | array | Additional options for sending the file. The following options are supported:
|
return | $this | The response object itself |
---|---|---|
throws | yii\web\RangeNotSatisfiableHttpException | if the requested range is not satisfiable |
Sets a default set of HTTP headers for file downloading purpose.
public $this setDownloadHeaders ( $attachmentName, $mimeType = null, $inline = false, $contentLength = null ) | ||
$attachmentName | string | The attachment file name |
$mimeType | string | The MIME type for the response. If null, |
$inline | boolean | Whether the browser should open the file within the browser window. Defaults to false, meaning a download dialog will pop up. |
$contentLength | integer | The byte length of the file being downloaded. If null, |
return | $this | The response object itself |
---|
Sets the response status code.
This method will set the corresponding status text if $text
is null.
public $this setStatusCode ( $value, $text = null ) | ||
$value | integer | The status code |
$text | string | The status text. If not set, it will be set automatically based on the status code. |
return | $this | The response object itself |
---|---|---|
throws | yii\base\InvalidArgumentException | if the status code is invalid. |
Sets the response status code based on the exception.
public $this setStatusCodeByException ( $e ) | ||
$e | Exception|Error | The exception object. |
return | $this | The response object itself |
---|---|---|
throws | yii\base\InvalidArgumentException | if the status code is invalid. |
Sends existing file to a browser as a download using x-sendfile.
X-Sendfile is a feature allowing a web application to redirect the request for a file to the webserver that in turn processes the request, this way eliminating the need to perform tasks like reading the file and sending it to the user. When dealing with a lot of files (or very big files) this can lead to a great increase in performance as the web application is allowed to terminate earlier while the webserver is handling the request.
The request is sent to the server through a special non-standard HTTP-header. When the web server encounters the presence of such header it will discard all output and send the file specified by that header using web server internals including all optimizations like caching-headers.
As this header directive is non-standard different directives exists for different web servers applications:
- Apache: X-Sendfile
- Lighttpd v1.4: X-LIGHTTPD-send-file
- Lighttpd v1.5: X-Sendfile
- Nginx: X-Accel-Redirect
- Cherokee: X-Sendfile and X-Accel-Redirect
So for this method to work the X-SENDFILE option/module should be enabled by the web server and a proper xHeader should be sent.
Note
This option allows to download files that are not under web folders, and even files that are otherwise protected
(deny from all) like .htaccess
.
Side effects
If this option is disabled by the web server, when this method is called a download configuration dialog will open but the downloaded file will have 0 bytes.
Known issues
There is a Bug with Internet Explorer 6, 7 and 8 when X-SENDFILE is used over an SSL connection, it will show
an error message like this: "Internet Explorer was not able to open this Internet site. The requested site
is either unavailable or cannot be found.". You can work around this problem by removing the Pragma
-header.
Example
Yii::$app->response->xSendFile('/home/user/Pictures/picture1.jpg');
See also sendFile().
public $this xSendFile ( $filePath, $attachmentName = null, $options = [] ) | ||
$filePath | string | File name with full path |
$attachmentName | string | File name shown to the user. If null, it will be determined from |
$options | array | Additional options for sending the file. The following options are supported:
|
return | $this | The response object itself |
---|
Signup or Login in order to comment.