# Response

> The web Response class represents an HTTP response.

[API reference](/docs/api/index.md) › [yii](/docs/api/yii/index.md) › [web](/docs/api/yii/web/index.md) › Response

| class | `yii\web\Response` |
| --- | --- |
| Extends | [`yii\base\Response`](/docs/api/yii/base/response/index.md) » [`yii\base\Component`](/docs/api/yii/base/component/index.md) » [`yii\base\BaseObject`](/docs/api/yii/base/baseobject/index.md) |
| Implements | [`yii\base\Configurable`](/docs/api/yii/base/configurable/index.md) |
| Since | 2.0 |
| Source | [`framework/web/Response.php`](https://github.com/yiisoft/yii2/blob/22.0/framework/web/Response.php#L63) |

1 subclass:

- [`yii2\extensions\psrbridge\http\Response`](/docs/extensions/psr-bridge/reference/http/response/index.md)

The web Response class represents an HTTP response.

It holds the [`$headers`](/docs/api/yii/web/response/index.md#property-headers), [`$cookies`](/docs/api/yii/web/response/index.md#property-cookies) and [`$content`](/docs/api/yii/web/response/index.md#property-content) that is to be sent to the client.
It also controls the HTTP [status code](/docs/api/yii/web/response/index.md#property-statusCode).

Response is configured as an application component in [`Application`](/docs/api/yii/web/application/index.md) 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](/docs/guide/runtime-responses/index.md).

## Properties

| Property | Type | Description | Defined by |
| --- | --- | --- | --- |
| [`$acceptMimeType`](#property-acceptMimeType) | `string\|null` | The MIME type (e.g. `application/json`) from the request ACCEPT header chosen for this response. Default: `null`. | `Response` |
| [`$acceptParams`](#property-acceptParams) | `array` | The parameters (e.g. `['q' => 1, 'version' => '1.0']`) associated with the [chosen MIME type](/docs/api/yii/web/response/index.md#property-acceptMimeType). Default: `[]`. | `Response` |
| <span id="property-behaviors"></span>[`$behaviors`](/docs/api/yii/base/component/index.md#property-behaviors) read-only | `array<`[`yii\base\Behavior`](/docs/api/yii/base/behavior/index.md)`<static>>` | List of behaviors attached to this component. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| [`$charset`](#property-charset) | `string\|null` | The charset of the text response. Default: `null`. | `Response` |
| [`$content`](#property-content) | `string\|null` | The response content. Default: `null`. | `Response` |
| <span id="property-cookies"></span>`$cookies` read-only | [`CookieCollection`](/docs/api/yii/web/cookiecollection/index.md) | The cookie collection. | `Response` |
| [`$data`](#property-data) | `mixed` | The original response data. Default: `null`. | `Response` |
| <span id="property-downloadHeaders"></span>`$downloadHeaders` write-only | `string` | The attachment file name. | `Response` |
| <span id="property-exitStatus"></span>[`$exitStatus`](/docs/api/yii/base/response/index.md#property-exitStatus) | `int` | The exit status. Default: `0`. | [`yii\base\Response`](/docs/api/yii/base/response/index.md) |
| [`$format`](#property-format) | `string` | The response format. Default: `self::FORMAT_HTML`. | `Response` |
| [`$formatters`](#property-formatters) | `array` | The formatters for converting data into the response content of the specified [`$format`](/docs/api/yii/web/response/index.md#property-format). Default: `[]`. | `Response` |
| <span id="property-headers"></span>`$headers` read-only | [`HeaderCollection`](/docs/api/yii/web/headercollection/index.md) | The header collection. | `Response` |
| <span id="property-httpStatuses"></span>`$httpStatuses` static | `array` | List of HTTP status codes and the corresponding texts Default: `[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']`. | `Response` |
| <span id="property-isClientError"></span>`$isClientError` read-only | `bool` | Whether this response indicates a client error. | `Response` |
| <span id="property-isEmpty"></span>`$isEmpty` read-only | `bool` | Whether this response is empty. | `Response` |
| <span id="property-isForbidden"></span>`$isForbidden` read-only | `bool` | Whether this response indicates the current request is forbidden. | `Response` |
| <span id="property-isInformational"></span>`$isInformational` read-only | `bool` | Whether this response is informational. | `Response` |
| <span id="property-isInvalid"></span>`$isInvalid` read-only | `bool` | Whether this response has a valid [`$statusCode`](/docs/api/yii/web/response/index.md#property-statusCode). | `Response` |
| <span id="property-isNotFound"></span>`$isNotFound` read-only | `bool` | Whether this response indicates the currently requested resource is not found. | `Response` |
| <span id="property-isOk"></span>`$isOk` read-only | `bool` | Whether this response is OK. | `Response` |
| <span id="property-isRedirection"></span>`$isRedirection` read-only | `bool` | Whether this response is a redirection. | `Response` |
| [`$isSent`](#property-isSent) | `bool` | Whether the response has been sent. Default: `false`. | `Response` |
| <span id="property-isServerError"></span>`$isServerError` read-only | `bool` | Whether this response indicates a server error. | `Response` |
| <span id="property-isSuccessful"></span>`$isSuccessful` read-only | `bool` | Whether this response is successful. | `Response` |
| <span id="property-statusCode"></span>`$statusCode` | `int` | The HTTP status code to send with the response. | `Response` |
| <span id="property-statusCodeByException"></span>`$statusCodeByException` write-only | [`Throwable`](https://www.php.net/manual/en/class.throwable.php) | The exception object. | `Response` |
| <span id="property-statusText"></span>`$statusText` | `string` | The HTTP status description that comes together with the status code. Default: `'OK'`. | `Response` |
| [`$stream`](#property-stream) | `resource\|array\|callable\|null` | The stream to be sent. Default: `null`. | `Response` |
| [`$version`](#property-version) | `string\|null` | The version of the HTTP protocol to use. Default: `null`. | `Response` |

## Methods

| Method | Description | Defined by |
| --- | --- | --- |
| <span id="method-__construct"></span>[`__construct()`](/docs/api/yii/base/baseobject/index.md#method-__construct) | Constructor. | [`yii\base\BaseObject`](/docs/api/yii/base/baseobject/index.md) |
| <span id="method-__call"></span>[`__call()`](/docs/api/yii/base/component/index.md#method-__call) | Calls the named method which is not a class method. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-__clone"></span>[`__clone()`](/docs/api/yii/base/component/index.md#method-__clone) | This method is called after the object is created by cloning an existing one. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-__get"></span>[`__get()`](/docs/api/yii/base/component/index.md#method-__get) | Returns the value of a component property. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-__isset"></span>[`__isset()`](/docs/api/yii/base/component/index.md#method-__isset) | Checks if a property is set, i.e. defined and not null. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-__set"></span>[`__set()`](/docs/api/yii/base/component/index.md#method-__set) | Sets the value of a component property. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-__unset"></span>[`__unset()`](/docs/api/yii/base/component/index.md#method-__unset) | Sets a component property to be null. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-attachBehavior"></span>[`attachBehavior()`](/docs/api/yii/base/component/index.md#method-attachBehavior) | Attaches a behavior to this component. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-attachBehaviors"></span>[`attachBehaviors()`](/docs/api/yii/base/component/index.md#method-attachBehaviors) | Attaches a list of behaviors to the component. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-behaviors"></span>[`behaviors()`](/docs/api/yii/base/component/index.md#method-behaviors) | Returns a list of behaviors that this component should behave as. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-canGetProperty"></span>[`canGetProperty()`](/docs/api/yii/base/component/index.md#method-canGetProperty) | Returns a value indicating whether a property can be read. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-canSetProperty"></span>[`canSetProperty()`](/docs/api/yii/base/component/index.md#method-canSetProperty) | Returns a value indicating whether a property can be set. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-className"></span>[`className()`](/docs/api/yii/base/baseobject/index.md#method-className) static | Returns the fully qualified name of this class. | [`yii\base\BaseObject`](/docs/api/yii/base/baseobject/index.md) |
| [`clear()`](#method-clear) | Clears the headers, cookies, content, status code of the response. | `Response` |
| <span id="method-clearOutputBuffers"></span>[`clearOutputBuffers()`](/docs/api/yii/base/response/index.md#method-clearOutputBuffers) | Removes all existing output buffers. | [`yii\base\Response`](/docs/api/yii/base/response/index.md) |
| <span id="method-detachBehavior"></span>[`detachBehavior()`](/docs/api/yii/base/component/index.md#method-detachBehavior) | Detaches a behavior from the component. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-detachBehaviors"></span>[`detachBehaviors()`](/docs/api/yii/base/component/index.md#method-detachBehaviors) | Detaches all behaviors from the component. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-ensureBehaviors"></span>[`ensureBehaviors()`](/docs/api/yii/base/component/index.md#method-ensureBehaviors) | Makes sure that the behaviors declared in [`behaviors()`](/docs/api/yii/base/component/index.md#method-behaviors) are attached to this component. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-getBehavior"></span>[`getBehavior()`](/docs/api/yii/base/component/index.md#method-getBehavior) | Returns the named behavior object. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-getBehaviors"></span>[`getBehaviors()`](/docs/api/yii/base/component/index.md#method-getBehaviors) | Returns all behaviors attached to this component. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| [`getCookies()`](#method-getCookies) | Returns the cookie collection. | `Response` |
| [`getHeaders()`](#method-getHeaders) | Returns the header collection. | `Response` |
| [`getIsClientError()`](#method-getIsClientError) |  | `Response` |
| [`getIsEmpty()`](#method-getIsEmpty) |  | `Response` |
| [`getIsForbidden()`](#method-getIsForbidden) |  | `Response` |
| [`getIsInformational()`](#method-getIsInformational) |  | `Response` |
| [`getIsInvalid()`](#method-getIsInvalid) |  | `Response` |
| [`getIsNotFound()`](#method-getIsNotFound) |  | `Response` |
| [`getIsOk()`](#method-getIsOk) |  | `Response` |
| [`getIsRedirection()`](#method-getIsRedirection) |  | `Response` |
| [`getIsServerError()`](#method-getIsServerError) |  | `Response` |
| [`getIsSuccessful()`](#method-getIsSuccessful) |  | `Response` |
| [`getStatusCode()`](#method-getStatusCode) |  | `Response` |
| <span id="method-hasEventHandlers"></span>[`hasEventHandlers()`](/docs/api/yii/base/component/index.md#method-hasEventHandlers) | Returns a value indicating whether there is any handler attached to the named event. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-hasMethod"></span>[`hasMethod()`](/docs/api/yii/base/component/index.md#method-hasMethod) | Returns a value indicating whether a method is defined. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-hasProperty"></span>[`hasProperty()`](/docs/api/yii/base/component/index.md#method-hasProperty) | Returns a value indicating whether a property is defined for this component. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| [`init()`](#method-init) | Initializes this component. | `Response` |
| <span id="method-off"></span>[`off()`](/docs/api/yii/base/component/index.md#method-off) | Detaches an existing event handler from this component. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-on"></span>[`on()`](/docs/api/yii/base/component/index.md#method-on) | Attaches an event handler to an event. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| [`redirect()`](#method-redirect) | Redirects the browser to the specified URL. | `Response` |
| [`refresh()`](#method-refresh) | Refreshes the current page. | `Response` |
| [`send()`](#method-send) | Sends the response to the client. | `Response` |
| [`sendContentAsFile()`](#method-sendContentAsFile) | Sends the specified content as a file to the browser. | `Response` |
| [`sendFile()`](#method-sendFile) | Sends a file to the browser. | `Response` |
| [`sendStreamAsFile()`](#method-sendStreamAsFile) | Sends the specified stream as a file to the browser. | `Response` |
| [`setDownloadHeaders()`](#method-setDownloadHeaders) | Sets a default set of HTTP headers for file downloading purpose. | `Response` |
| [`setStatusCode()`](#method-setStatusCode) | Sets the response status code. | `Response` |
| [`setStatusCodeByException()`](#method-setStatusCodeByException) | Sets the response status code based on the exception. | `Response` |
| <span id="method-trigger"></span>[`trigger()`](/docs/api/yii/base/component/index.md#method-trigger) | Triggers an event. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| [`xSendFile()`](#method-xSendFile) | Sends existing file to a browser as a download using x-sendfile. | `Response` |
| [`defaultFormatters()`](#method-defaultFormatters) protected |  | `Response` |
| [`getDispositionHeaderValue()`](#method-getDispositionHeaderValue) protected | Returns Content-Disposition header value that is safe to use with both old and new browsers. | `Response` |
| [`getHttpRange()`](#method-getHttpRange) protected | Determines the HTTP range given in the request. | `Response` |
| [`prepare()`](#method-prepare) protected | Prepares for sending the response. | `Response` |
| [`sendContent()`](#method-sendContent) protected | Sends the response content to the client. | `Response` |
| [`sendCookies()`](#method-sendCookies) protected | Sends the cookies to the client. | `Response` |
| [`sendHeaders()`](#method-sendHeaders) protected | Sends the response headers to the client. | `Response` |

## Events

| Event | Type | Description | Defined by |
| --- | --- | --- | --- |
| <span id="event-EVENT_BEFORE_SEND"></span>`EVENT_BEFORE_SEND` | [`yii\base\Event`](/docs/api/yii/base/event/index.md) | An event that is triggered at the beginning of [`send()`](/docs/api/yii/web/response/index.md#method-send). Event name: `'beforeSend'`. | `Response` |
| <span id="event-EVENT_AFTER_SEND"></span>`EVENT_AFTER_SEND` | [`yii\base\Event`](/docs/api/yii/base/event/index.md) | An event that is triggered at the end of [`send()`](/docs/api/yii/web/response/index.md#method-send). Event name: `'afterSend'`. | `Response` |
| <span id="event-EVENT_AFTER_PREPARE"></span>`EVENT_AFTER_PREPARE` | [`yii\base\Event`](/docs/api/yii/base/event/index.md) | An event that is triggered right after [`prepare()`](/docs/api/yii/web/response/index.md#method-prepare) is called in [`send()`](/docs/api/yii/web/response/index.md#method-send). Event name: `'afterPrepare'`. | `Response` |

## Constants

| Constant | Value | Description | Defined by |
| --- | --- | --- | --- |
| <span id="const-FORMAT_RAW"></span>`FORMAT_RAW` | `'raw'` |  | `Response` |
| <span id="const-FORMAT_HTML"></span>`FORMAT_HTML` | `'html'` |  | `Response` |
| <span id="const-FORMAT_JSON"></span>`FORMAT_JSON` | `'json'` |  | `Response` |
| <span id="const-FORMAT_JSONP"></span>`FORMAT_JSONP` | `'jsonp'` |  | `Response` |
| <span id="const-FORMAT_XML"></span>`FORMAT_XML` | `'xml'` |  | `Response` |

## Property details

### $acceptMimeType <span id="property-acceptMimeType"></span>

```php
public string|null $acceptMimeType = null
```

The MIME type (e.g. `application/json`) from the request ACCEPT header chosen for this response.

This property is mainly set by [`ContentNegotiator`](/docs/api/yii/filters/contentnegotiator/index.md).

### $acceptParams <span id="property-acceptParams"></span>

```php
public array $acceptParams = []
```

The parameters (e.g. `['q' => 1, 'version' => '1.0']`) associated with the [chosen MIME type](/docs/api/yii/web/response/index.md#property-acceptMimeType).

This is a list of name-value pairs associated with [`$acceptMimeType`](/docs/api/yii/web/response/index.md#property-acceptMimeType) from the ACCEPT HTTP header.
This property is mainly set by [`ContentNegotiator`](/docs/api/yii/filters/contentnegotiator/index.md).

### $charset <span id="property-charset"></span>

```php
public string|null $charset = null
```

The charset of the text response.

If not set, it will use
the value of [`Application::$charset`](/docs/api/yii/base/application/index.md#property-charset).

### $content <span id="property-content"></span>

```php
public string|null $content = null
```

The response content.

When [`$data`](/docs/api/yii/web/response/index.md#property-data) is not null, it will be converted into [`$content`](/docs/api/yii/web/response/index.md#property-content)
according to [`$format`](/docs/api/yii/web/response/index.md#property-format) when the response is being sent out.

### $data <span id="property-data"></span>

```php
public mixed $data = null
```

The original response data.

When this is not null, it will be converted into [`$content`](/docs/api/yii/web/response/index.md#property-content)
according to [`$format`](/docs/api/yii/web/response/index.md#property-format) when the response is being sent out.

### $format <span id="property-format"></span>

```php
public string $format = self::FORMAT_HTML
```

The response format.

This determines how to convert [`$data`](/docs/api/yii/web/response/index.md#property-data) into [`$content`](/docs/api/yii/web/response/index.md#property-content)
when the latter is not set. The value of this property must be one of the keys declared in the [`$formatters`](/docs/api/yii/web/response/index.md#property-formatters) array.
By default, the following formats are supported:

- [`FORMAT_RAW`](/docs/api/yii/web/response/index.md#const-FORMAT_RAW): the data will be treated as the response content without any conversion.
  No extra HTTP header will be added.
- [`FORMAT_HTML`](/docs/api/yii/web/response/index.md#const-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`](/docs/api/yii/web/response/index.md#const-FORMAT_JSON): the data will be converted into JSON format, and the "Content-Type"
  header will be set as "application/json".
- [`FORMAT_JSONP`](/docs/api/yii/web/response/index.md#const-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`](/docs/api/yii/web/response/index.md#const-FORMAT_XML): the data will be converted into XML format. Please refer to [`XmlResponseFormatter`](/docs/api/yii/web/xmlresponseformatter/index.md)
  for more details.

You may customize the formatting process or support additional formats by configuring [`$formatters`](/docs/api/yii/web/response/index.md#property-formatters).

### $formatters <span id="property-formatters"></span>

```php
public array $formatters = []
```

The formatters for converting data into the response content of the specified [`$format`](/docs/api/yii/web/response/index.md#property-format).

The array keys are the format names, and the array values are the corresponding configurations
for creating the formatter objects.

### $isSent <span id="property-isSent"></span>

```php
public bool $isSent = false
```

Whether the response has been sent.

If this is true, calling [`send()`](/docs/api/yii/web/response/index.md#method-send) will do nothing.

### $stream <span id="property-stream"></span>

```php
public resource|array|callable|null $stream = null
```

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](https://www.php.net/manual/en/language.generators.syntax.php)) an array of strings that should
be echoed and flushed out one by one.

Note that when this property is set, the [`$data`](/docs/api/yii/web/response/index.md#property-data) and [`$content`](/docs/api/yii/web/response/index.md#property-content) properties will be ignored by [`send()`](/docs/api/yii/web/response/index.md#method-send).

### $version <span id="property-version"></span>

```php
public string|null $version = null
```

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

### clear() <span id="method-clear"></span>

```php
public function clear(): mixed
```

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

**Returns**

`mixed`

### getCookies() <span id="method-getCookies"></span>

```php
public function getCookies(): yii\web\CookieCollection
```

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']);
```

**Returns**

[`CookieCollection`](/docs/api/yii/web/cookiecollection/index.md): The cookie collection.

### getHeaders() <span id="method-getHeaders"></span>

```php
public function getHeaders(): yii\web\HeaderCollection
```

Returns the header collection.

The header collection contains the currently registered HTTP headers.

**Returns**

[`HeaderCollection`](/docs/api/yii/web/headercollection/index.md): The header collection

### getIsClientError() <span id="method-getIsClientError"></span>

```php
public function getIsClientError(): bool
```

**Returns**

`bool`: Whether this response indicates a client error

### getIsEmpty() <span id="method-getIsEmpty"></span>

```php
public function getIsEmpty(): bool
```

**Returns**

`bool`: Whether this response is empty

### getIsForbidden() <span id="method-getIsForbidden"></span>

```php
public function getIsForbidden(): bool
```

**Returns**

`bool`: Whether this response indicates the current request is forbidden

### getIsInformational() <span id="method-getIsInformational"></span>

```php
public function getIsInformational(): bool
```

**Returns**

`bool`: Whether this response is informational

### getIsInvalid() <span id="method-getIsInvalid"></span>

```php
public function getIsInvalid(): bool
```

**Returns**

`bool`: Whether this response has a valid [`$statusCode`](/docs/api/yii/web/response/index.md#property-statusCode).

### getIsNotFound() <span id="method-getIsNotFound"></span>

```php
public function getIsNotFound(): bool
```

**Returns**

`bool`: Whether this response indicates the currently requested resource is not found

### getIsOk() <span id="method-getIsOk"></span>

```php
public function getIsOk(): bool
```

**Returns**

`bool`: Whether this response is OK

### getIsRedirection() <span id="method-getIsRedirection"></span>

```php
public function getIsRedirection(): bool
```

**Returns**

`bool`: Whether this response is a redirection

### getIsServerError() <span id="method-getIsServerError"></span>

```php
public function getIsServerError(): bool
```

**Returns**

`bool`: Whether this response indicates a server error

### getIsSuccessful() <span id="method-getIsSuccessful"></span>

```php
public function getIsSuccessful(): bool
```

**Returns**

`bool`: Whether this response is successful

### getStatusCode() <span id="method-getStatusCode"></span>

```php
public function getStatusCode(): int
```

**Returns**

`int`: The HTTP status code to send with the response.

### init() <span id="method-init"></span>

```php
public function init(): mixed
```

Initializes this component.

**Returns**

`mixed`

### redirect() <span id="method-redirect"></span>

```php
public function redirect(string|array $url, int $statusCode = 302, bool $checkAjax = true): $this
```

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()`](/docs/api/yii/web/response/index.md#method-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;
    }
});
```

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$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. [`Url::to()`](/docs/api/yii/helpers/baseurl/index.md#method-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` | `int` | The HTTP status code. Defaults to 302. See <https://tools.ietf.org/html/rfc2616#section-10> for details about HTTP status code |
| `$checkAjax` | `bool` | 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. |

**Returns**

`$this`: The response object itself

### refresh() <span id="method-refresh"></span>

```php
public function refresh(string $anchor = ''): yii\web\Response
```

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

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$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. |

**Returns**

[`Response`](/docs/api/yii/web/response/index.md): The response object itself

### send() <span id="method-send"></span>

```php
public function send(): mixed
```

Sends the response to the client.

**Returns**

`mixed`

### sendContentAsFile() <span id="method-sendContentAsFile"></span>

```php
public function sendContentAsFile(string $content, string $attachmentName, array $options = []): $this
```

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()`](/docs/api/yii/web/response/index.md#method-send) is called explicitly or implicitly. The latter is done after you return from a controller action.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$content` | `string` | The content to be sent. The existing [`$content`](/docs/api/yii/web/response/index.md#property-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**

`$this`: The response object itself

**Throws**

- [`RangeNotSatisfiableHttpException`](/docs/api/yii/web/rangenotsatisfiablehttpexception/index.md): if the requested range is not satisfiable

**See also**

- [`sendFile()`](/docs/api/yii/web/response/index.md#method-sendFile) (for an example implementation.)

### sendFile() <span id="method-sendFile"></span>

```php
public function sendFile(string $filePath, string|null $attachmentName = null, array $options = []): $this
```

Sends a file to the browser.

Note that this method only prepares the response for file sending. The file is not sent
until [`send()`](/docs/api/yii/web/response/index.md#method-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);
}
```

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$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**

`$this`: The response object itself

**See also**

- [`sendContentAsFile()`](/docs/api/yii/web/response/index.md#method-sendContentAsFile)
- [`sendStreamAsFile()`](/docs/api/yii/web/response/index.md#method-sendStreamAsFile)
- [`xSendFile()`](/docs/api/yii/web/response/index.md#method-xSendFile)

### sendStreamAsFile() <span id="method-sendStreamAsFile"></span>

```php
public function sendStreamAsFile(resource $handle, string $attachmentName, array $options = []): $this
```

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()`](/docs/api/yii/web/response/index.md#method-send) is called explicitly or implicitly. The latter is done after you return from a controller action.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$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. |

**Returns**

`$this`: The response object itself

**Throws**

- [`RangeNotSatisfiableHttpException`](/docs/api/yii/web/rangenotsatisfiablehttpexception/index.md): if the requested range is not satisfiable

**See also**

- [`sendFile()`](/docs/api/yii/web/response/index.md#method-sendFile) (for an example implementation.)

### setDownloadHeaders() <span id="method-setDownloadHeaders"></span>

```php
public function setDownloadHeaders(string $attachmentName, string|null $mimeType = null, bool $inline = false, int|null $contentLength = null): $this
```

Sets a default set of HTTP headers for file downloading purpose.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$attachmentName` | `string` | The attachment file name |
| `$mimeType` | `string\|null` | The MIME type for the response. If null, `Content-Type` header will NOT be set. |
| `$inline` | `bool` | Whether the browser should open the file within the browser window. Defaults to false, meaning a download dialog will pop up. |
| `$contentLength` | `int\|null` | The byte length of the file being downloaded. If null, `Content-Length` header will NOT be set. |

**Returns**

`$this`: The response object itself

### setStatusCode() <span id="method-setStatusCode"></span>

```php
public function setStatusCode(int $value, string|null $text = null): $this
```

Sets the response status code.

This method will set the corresponding status text if `$text` is null.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$value` | `int` | The status code |
| `$text` | `string\|null` | The status text. If not set, it will be set automatically based on the status code. |

**Returns**

`$this`: The response object itself

**Throws**

- [`yii\base\InvalidArgumentException`](/docs/api/yii/base/invalidargumentexception/index.md): if the status code is invalid.

### setStatusCodeByException() <span id="method-setStatusCodeByException"></span>

```php
public function setStatusCodeByException(Throwable $e): $this
```

Sets the response status code based on the exception.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$e` | [`Throwable`](https://www.php.net/manual/en/class.throwable.php) | The exception object. |

**Returns**

`$this`: The response object itself

**Throws**

- [`yii\base\InvalidArgumentException`](/docs/api/yii/base/invalidargumentexception/index.md): if the status code is invalid.

**Since**

2.0.12

### xSendFile() <span id="method-xSendFile"></span>

```php
public function xSendFile(string $filePath, string|null $attachmentName = null, array $options = []): $this
```

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](https://tn123.org/mod_xsendfile/)
- Lighttpd v1.4: [X-LIGHTTPD-send-file](https://redmine.lighttpd.net/projects/lighttpd/wiki/X-LIGHTTPD-send-file)
- Lighttpd v1.5: [X-Sendfile](https://redmine.lighttpd.net/projects/lighttpd/wiki/X-LIGHTTPD-send-file)
- Nginx: [X-Accel-Redirect](https://www.nginx.com/resources/wiki/XSendfile)
- Cherokee: [X-Sendfile and X-Accel-Redirect](https://cherokee-project.com/doc/other_goodies.html#x-sendfile)

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');
```

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$filePath` | `string` | File name with full path |
| `$attachmentName` | `string\|null` | 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". |

**Returns**

`$this`: The response object itself

**See also**

- [`sendFile()`](/docs/api/yii/web/response/index.md#method-sendFile)

### defaultFormatters() <span id="method-defaultFormatters"></span>

```php
protected function defaultFormatters(): array
```

**Returns**

`array`: The formatters that are supported by default

### getDispositionHeaderValue() <span id="method-getDispositionHeaderValue"></span>

```php
protected function getDispositionHeaderValue(string $disposition, string $attachmentName): string
```

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.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$disposition` | `string` |  |
| `$attachmentName` | `string` |  |

**Returns**

`string`

**Since**

2.0.10

### getHttpRange() <span id="method-getHttpRange"></span>

```php
protected function getHttpRange(int $fileSize): array|bool
```

Determines the HTTP range given in the request.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$fileSize` | `int` | The size of the file that will be used to validate the requested HTTP range. |

**Returns**

`array|bool`: The range (begin, end), or false if the range request is invalid.

### prepare() <span id="method-prepare"></span>

```php
protected function prepare(): mixed
```

Prepares for sending the response.

The default implementation will convert [`$data`](/docs/api/yii/web/response/index.md#property-data) into [`$content`](/docs/api/yii/web/response/index.md#property-content) and set headers accordingly.

**Returns**

`mixed`

**Throws**

- [`yii\base\InvalidConfigException`](/docs/api/yii/base/invalidconfigexception/index.md): if the formatter for the specified format is invalid or [`$format`](/docs/api/yii/web/response/index.md#property-format) is not supported

**See also**

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

### sendContent() <span id="method-sendContent"></span>

```php
protected function sendContent(): mixed
```

Sends the response content to the client.

**Returns**

`mixed`

### sendCookies() <span id="method-sendCookies"></span>

```php
protected function sendCookies(): mixed
```

Sends the cookies to the client.

**Returns**

`mixed`

### sendHeaders() <span id="method-sendHeaders"></span>

```php
protected function sendHeaders(): mixed
```

Sends the response headers to the client.

**Returns**

`mixed`