# 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

Hide inherited 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. This property is read-only. | 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. This property is read-only. | yii\web\Response
$data | mixed | The original response data. | yii\web\Response
$downloadHeaders | string | The attachment file name. This property is write-only. | 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. This property is read-only. | 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. This property is read-only. | yii\web\Response
$isEmpty | boolean | Whether this response is empty. This property is read-only. | yii\web\Response
$isForbidden | boolean | Whether this response indicates the current request is forbidden. This property is read-only. | yii\web\Response
$isInformational | boolean | Whether this response is informational. This property is read-only. | yii\web\Response
$isInvalid | boolean | Whether this response has a valid $statusCode. This property is read-only. | yii\web\Response
$isNotFound | boolean | Whether this response indicates the currently requested resource is not found. This property is read-only. | yii\web\Response
$isOk | boolean | Whether this response is OK. This property is read-only. | yii\web\Response
$isRedirection | boolean | Whether this response is a redirection. This property is read-only. | yii\web\Response
$isSent | boolean | Whether the response has been sent. | yii\web\Response
$isServerError | boolean | Whether this response indicates a server error. This property is read-only. | yii\web\Response
$isSuccessful | boolean | Whether this response is successful. This property is read-only. | yii\web\Response
$statusCode | integer | The HTTP status code to send with the response. | yii\web\Response
$statusCodeByException | Exception|Error|Throwable | The exception object. This property is write-only. | yii\web\Response
$statusText | string | The HTTP status description that comes together with the status code. | yii\web\Response
$stream | resource|array|callable | The stream to be sent. | yii\web\Response
$version | string | The version of the HTTP protocol to use. | yii\web\Response

## Public Methods

Hide inherited 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

Hide inherited 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

Hide inherited events

Event | Type | Description | Defined By
--- | --- | --- | ---
EVENT_AFTER_PREPARE | yii\base\Event | An event that is triggered right after prepare() is called in send(). | yii\web\Response
EVENT_AFTER_SEND | yii\base\Event | An event that is triggered at the end of send(). | yii\web\Response
EVENT_BEFORE_SEND | yii\base\Event | An event that is triggered at the beginning of send(). | yii\web\Response

## Constants

Hide inherited 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

$acceptMimeType public property

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.

public string $acceptMimeType = null
$acceptParams public property

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.

public array $acceptParams = []
$charset public property

The charset of the text response. If not set, it will use the value of yii\web\Application::$charset.

public string $charset = null
$content public property

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.

public string $content = null
$cookies public property

The cookie collection. This property is read-only.

public yii\web\CookieCollection $cookies = null
$data public property

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.

public mixed $data = null
$downloadHeaders public property

The attachment file name. This property is write-only.

public string $downloadHeaders = null
$format public property

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.

public string $format = self::FORMAT_HTML
$formatters public property

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:

- $format
- defaultFormatters()

public array $formatters = []
$headers public property

The header collection. This property is read-only.

public yii\web\HeaderCollection $headers = null
$httpStatuses public static property

List of HTTP status codes and the corresponding texts

public static array $httpStatuses = [100 => 'Continue', 101 => 'Switching Protocols', 102 => 'Processing', 118 => 'Connection timed out', 200 => 'OK', 201 => 'Created', 202 => 'Accepted', 203 => 'Non-Authoritative', 204 => 'No Content', 205 => 'Reset Content', 206 => 'Partial Content', 207 => 'Multi-Status', 208 => 'Already Reported', 210 => 'Content Different', 226 => 'IM Used', 300 => 'Multiple Choices', 301 => 'Moved Permanently', 302 => 'Found', 303 => 'See Other', 304 => 'Not Modified', 305 => 'Use Proxy', 306 => 'Reserved', 307 => 'Temporary Redirect', 308 => 'Permanent Redirect', 310 => 'Too many Redirect', 400 => 'Bad Request', 401 => 'Unauthorized', 402 => 'Payment Required', 403 => 'Forbidden', 404 => 'Not Found', 405 => 'Method Not Allowed', 406 => 'Not Acceptable', 407 => 'Proxy Authentication Required', 408 => 'Request Time-out', 409 => 'Conflict', 410 => 'Gone', 411 => 'Length Required', 412 => 'Precondition Failed', 413 => 'Request Entity Too Large', 414 => 'Request-URI Too Long', 415 => 'Unsupported Media Type', 416 => 'Requested range unsatisfiable', 417 => 'Expectation failed', 418 => 'I\'m a teapot', 421 => 'Misdirected Request', 422 => 'Unprocessable entity', 423 => 'Locked', 424 => 'Method failure', 425 => 'Unordered Collection', 426 => 'Upgrade Required', 428 => 'Precondition Required', 429 => 'Too Many Requests', 431 => 'Request Header Fields Too Large', 449 => 'Retry With', 450 => 'Blocked by Windows Parental Controls', 451 => 'Unavailable For Legal Reasons', 500 => 'Internal Server Error', 501 => 'Not Implemented', 502 => 'Bad Gateway or Proxy Error', 503 => 'Service Unavailable', 504 => 'Gateway Time-out', 505 => 'HTTP Version not supported', 507 => 'Insufficient storage', 508 => 'Loop Detected', 509 => 'Bandwidth Limit Exceeded', 510 => 'Not Extended', 511 => 'Network Authentication Required']
$isClientError public property

Whether this response indicates a client error. This property is read-only.

public boolean $isClientError = null
$isEmpty public property

Whether this response is empty. This property is read-only.

public boolean $isEmpty = null
$isForbidden public property

Whether this response indicates the current request is forbidden. This property is read-only.

public boolean $isForbidden = null
$isInformational public property

Whether this response is informational. This property is read-only.

public boolean $isInformational = null
$isInvalid public property

Whether this response has a valid $statusCode. This property is read-only.

public boolean $isInvalid = null
$isNotFound public property

Whether this response indicates the currently requested resource is not found. This property is read-only.

public boolean $isNotFound = null
$isOk public property

Whether this response is OK. This property is read-only.

public boolean $isOk = null
$isRedirection public property

Whether this response is a redirection. This property is read-only.

public boolean $isRedirection = null
$isSent public property

Whether the response has been sent. If this is true, calling send() will do nothing.

public boolean $isSent = false
$isServerError public property

Whether this response indicates a server error. This property is read-only.

public boolean $isServerError = null
$isSuccessful public property

Whether this response is successful. This property is read-only.

public boolean $isSuccessful = null
$statusCode public property

The HTTP status code to send with the response.

public integer $statusCode = null
$statusCodeByException public property

The exception object. This property is write-only.

public Exception|Error|Throwable $statusCodeByException = null
$statusText public property

The HTTP status description that comes together with the status code.

See also $httpStatuses.

public string $statusText = 'OK'
$stream public property

The stream to be sent. This can be a stream handle or an array of stream handle, the begin position and the end position. Alternatively it can be set to a callable, which returns (or yields) an array of strings that should be echoed and flushed out one by one.

Note that when this property is set, the $data and $content properties will be ignored by send().

public resource|array|callable $stream = null
$version public property

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.

public string $version = null

## Method Details

clear() public method

Clears the headers, cookies, content, status code of the response.

public void clear ( )

defaultFormatters() protected method

protected array defaultFormatters ( )
return | array | The formatters that are supported by default

getCookies() public method

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.

getDispositionHeaderValue() protected method (available since version 2.0.10)

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 interpret `filename="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 |

getHeaders() public method

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

getHttpRange() protected method

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.

getIsClientError() public method

public boolean getIsClientError ( )
return | boolean | Whether this response indicates a client error

getIsEmpty() public method

public boolean getIsEmpty ( )
return | boolean | Whether this response is empty

getIsForbidden() public method

public boolean getIsForbidden ( )
return | boolean | Whether this response indicates the current request is forbidden

getIsInformational() public method

public boolean getIsInformational ( )
return | boolean | Whether this response is informational

getIsInvalid() public method

public boolean getIsInvalid ( )
return | boolean | Whether this response has a valid $statusCode.

getIsNotFound() public method

public boolean getIsNotFound ( )
return | boolean | Whether this response indicates the currently requested resource is not found

getIsOk() public method

public boolean getIsOk ( )
return | boolean | Whether this response is OK

getIsRedirection() public method

public boolean getIsRedirection ( )
return | boolean | Whether this response is a redirection

getIsServerError() public method

public boolean getIsServerError ( )
return | boolean | Whether this response indicates a server error

getIsSuccessful() public method

public boolean getIsSuccessful ( )
return | boolean | Whether this response is successful

getStatusCode() public method

public integer getStatusCode ( )
return | integer | The HTTP status code to send with the response.

init() public method

Initializes this component.

public void init ( )

prepare() protected method

Prepares for sending the response.

The default implementation will convert $data into $content and set headers accordingly.

See also:

- https://tools.ietf.org/html/rfc7231#page-53
- https://tools.ietf.org/html/rfc7232#page-18

protected void prepare ( )
throws | yii\base\InvalidConfigException | if the formatter for the specified format is invalid or $format is not supported

redirect() public method

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:

- a string representing a URL (e.g. "http://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, a `Location` header will be sent, which when received as an AJAX/PJAX response, may NOT cause browser redirection. Takes effect only when request header `X-Ie-Redirect-Compatibility` is absent.

return | $this | The response object itself

refresh() public method

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

send() public method

Sends the response to the client.

public void send ( )

sendContent() protected method

Sends the response content to the client.

protected void sendContent ( )

sendContentAsFile() public method

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:

- `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.

return | $this | The response object itself
throws | yii\web\RangeNotSatisfiableHttpException | if the requested range is not satisfiable

sendCookies() protected method

Sends the cookies to the client.

protected void sendCookies ( )

sendFile() public method

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:

- sendContentAsFile()
- sendStreamAsFile()
- xSendFile()

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 `$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.

return | $this | The response object itself

sendHeaders() protected method

Sends the response headers to the client.

protected void sendHeaders ( )

sendStreamAsFile() public method

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:

- `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.
- `fileSize`: the size of the content to stream this is useful when size of the content is known and the content is not seekable. Defaults to content size using `ftell()`. This option is available since version 2.0.4.

return | $this | The response object itself
throws | yii\web\RangeNotSatisfiableHttpException | if the requested range is not satisfiable

setDownloadHeaders() public method

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, `Content-Type` header will NOT be set.
$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, `Content-Length` header will NOT be set.
return | $this | The response object itself

setStatusCode() public method

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.

setStatusCodeByException() public method (available since version 2.0.12)

Sets the response status code based on the exception.

public $this setStatusCodeByException ( $e )
$e | Exception|Error|Throwable | The exception object.
return | $this | The response object itself
throws | yii\base\InvalidArgumentException | if the status code is invalid.

xSendFile() public method

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 `$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.
- xHeader: string, the name of the x-sendfile header. Defaults to "X-Sendfile".

return | $this | The response object itself

## Event Details

EVENT_AFTER_PREPARE event of type yii\base\Event

An event that is triggered right after prepare() is called in send(). You may respond to this event to filter the response content before it is sent to the client.

EVENT_AFTER_SEND event of type yii\base\Event

An event that is triggered at the end of send().

EVENT_BEFORE_SEND event of type yii\base\Event

An event that is triggered at the beginning of send().