Skip to content
PHP Ecosystem
Explore

Response

API reference › yii › web › Response

1 subclass

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

PropertyTypeDescriptionDefined by
$acceptMimeTypestring|nullThe MIME type (e.g. application/json) from the request ACCEPT header chosen for this response. Default: null.Response
$acceptParamsarrayThe parameters (e.g. ['q' => 1, 'version' => '1.0']) associated with the chosen MIME type. Default: [].Response
$behaviors read-onlyarray<yii\base\Behavior<static>>List of behaviors attached to this component.yii\base\Component
$charsetstring|nullThe charset of the text response. Default: null.Response
$contentstring|nullThe response content. Default: null.Response
$cookies read-onlyCookieCollectionThe cookie collection.Response
$datamixedThe original response data. Default: null.Response
$downloadHeaders write-onlystringThe attachment file name.Response
$exitStatusintThe exit status. Default: 0.yii\base\Response
$formatstringThe response format. Default: self::FORMAT_HTML.Response
$formattersarrayThe formatters for converting data into the response content of the specified $format. Default: [].Response
$headers read-onlyHeaderCollectionThe header collection.Response
$httpStatuses staticarrayList 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
$isClientError read-onlyboolWhether this response indicates a client error.Response
$isEmpty read-onlyboolWhether this response is empty.Response
$isForbidden read-onlyboolWhether this response indicates the current request is forbidden.Response
$isInformational read-onlyboolWhether this response is informational.Response
$isInvalid read-onlyboolWhether this response has a valid $statusCode.Response
$isNotFound read-onlyboolWhether this response indicates the currently requested resource is not found.Response
$isOk read-onlyboolWhether this response is OK.Response
$isRedirection read-onlyboolWhether this response is a redirection.Response
$isSentboolWhether the response has been sent. Default: false.Response
$isServerError read-onlyboolWhether this response indicates a server error.Response
$isSuccessful read-onlyboolWhether this response is successful.Response
$statusCodeintThe HTTP status code to send with the response.Response
$statusCodeByException write-onlyThrowableThe exception object.Response
$statusTextstringThe HTTP status description that comes together with the status code. Default: 'OK'.Response
$streamresource|array|callable|nullThe stream to be sent. Default: null.Response
$versionstring|nullThe version of the HTTP protocol to use. Default: null.Response
MethodDescriptionDefined by
__construct()Constructor.yii\base\BaseObject
__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
__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() staticReturns the fully qualified name of this class.yii\base\BaseObject
clear()Clears the headers, cookies, content, status code of the response.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.Response
getHeaders()Returns the header collection.Response
getIsClientError()Response
getIsEmpty()Response
getIsForbidden()Response
getIsInformational()Response
getIsInvalid()Response
getIsNotFound()Response
getIsOk()Response
getIsRedirection()Response
getIsServerError()Response
getIsSuccessful()Response
getStatusCode()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.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.Response
refresh()Refreshes the current page.Response
send()Sends the response to the client.Response
sendContentAsFile()Sends the specified content as a file to the browser.Response
sendFile()Sends a file to the browser.Response
sendStreamAsFile()Sends the specified stream as a file to the browser.Response
setDownloadHeaders()Sets a default set of HTTP headers for file downloading purpose.Response
setStatusCode()Sets the response status code.Response
setStatusCodeByException()Sets the response status code based on the exception.Response
trigger()Triggers an event.yii\base\Component
xSendFile()Sends existing file to a browser as a download using x-sendfile.Response
defaultFormatters() protectedResponse
getDispositionHeaderValue() protectedReturns Content-Disposition header value that is safe to use with both old and new browsers.Response
getHttpRange() protectedDetermines the HTTP range given in the request.Response
prepare() protectedPrepares for sending the response.Response
sendContent() protectedSends the response content to the client.Response
sendCookies() protectedSends the cookies to the client.Response
sendHeaders() protectedSends the response headers to the client.Response
EventTypeDescriptionDefined by
EVENT_BEFORE_SENDyii\base\EventAn event that is triggered at the beginning of send(). Event name: 'beforeSend'.Response
EVENT_AFTER_SENDyii\base\EventAn event that is triggered at the end of send(). Event name: 'afterSend'.Response
EVENT_AFTER_PREPAREyii\base\EventAn event that is triggered right after prepare() is called in send(). Event name: 'afterPrepare'.Response
ConstantValueDescriptionDefined by
FORMAT_RAW'raw'Response
FORMAT_HTML'html'Response
FORMAT_JSON'json'Response
FORMAT_JSONP'jsonp'Response
FORMAT_XML'xml'Response
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.

public array $acceptParams = []

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

public string|null $charset = null

The charset of the text response.

If not set, it will use the value of Application::$charset.

public string|null $content = null

The response content.

When $data is not null, it will be converted into $content according to $format when the response is being sent out.

public mixed $data = null

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.

public string $format = self::FORMAT_HTML

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 XmlResponseFormatter for more details.

You may customize the formatting process or support additional formats by configuring $formatters.

public array $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.

public bool $isSent = false

Whether the response has been sent.

If this is true, calling send() will do nothing.

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

public function clear(): mixed

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

Returns

mixed

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: The cookie collection.

public function getHeaders(): yii\web\HeaderCollection

Returns the header collection.

The header collection contains the currently registered HTTP headers.

Returns

HeaderCollection: The header collection

public function getIsClientError(): bool

Returns

bool: Whether this response indicates a client error

public function getIsEmpty(): bool

Returns

bool: Whether this response is empty

public function getIsForbidden(): bool

Returns

bool: Whether this response indicates the current request is forbidden

public function getIsInformational(): bool

Returns

bool: Whether this response is informational

public function getIsInvalid(): bool

Returns

bool: Whether this response has a valid $statusCode.

public function getIsNotFound(): bool

Returns

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

public function getIsOk(): bool

Returns

bool: Whether this response is OK

public function getIsRedirection(): bool

Returns

bool: Whether this response is a redirection

public function getIsServerError(): bool

Returns

bool: Whether this response indicates a server error

public function getIsSuccessful(): bool

Returns

bool: Whether this response is successful

public function getStatusCode(): int

Returns

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

public function init(): mixed

Initializes this component.

Returns

mixed

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

ParameterTypeDescription
$urlstring|arrayThe 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() 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.
$statusCodeintThe HTTP status code. Defaults to 302. See https://tools.ietf.org/html/rfc2616#section-10 for details about HTTP status code
$checkAjaxboolWhether 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

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

ParameterTypeDescription
$anchorstringThe 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: The response object itself

public function send(): mixed

Sends the response to the client.

Returns

mixed

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() is called explicitly or implicitly. The latter is done after you return from a controller action.

Parameters

ParameterTypeDescription
$contentstringThe content to be sent. The existing $content will be discarded.
$attachmentNamestringThe file name shown to the user.
$optionsarrayAdditional 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

See also

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

ParameterTypeDescription
$filePathstringThe path of the file to be sent.
$attachmentNamestring|nullThe file name shown to the user. If null, it will be determined from $filePath.
$optionsarrayAdditional 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

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() is called explicitly or implicitly. The latter is done after you return from a controller action.

Parameters

ParameterTypeDescription
$handleresourceThe handle of the stream to be sent.
$attachmentNamestringThe file name shown to the user.
$optionsarrayAdditional 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

See also

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

ParameterTypeDescription
$attachmentNamestringThe attachment file name
$mimeTypestring|nullThe MIME type for the response. If null, Content-Type header will NOT be set.
$inlineboolWhether the browser should open the file within the browser window. Defaults to false, meaning a download dialog will pop up.
$contentLengthint|nullThe byte length of the file being downloaded. If null, Content-Length header will NOT be set.

Returns

$this: The response object itself

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

ParameterTypeDescription
$valueintThe status code
$textstring|nullThe status text. If not set, it will be set automatically based on the status code.

Returns

$this: The response object itself

Throws

public function setStatusCodeByException(Throwable $e): $this

Sets the response status code based on the exception.

Parameters

ParameterTypeDescription
$eThrowableThe exception object.

Returns

$this: The response object itself

Throws

Since

2.0.12

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:

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

ParameterTypeDescription
$filePathstringFile name with full path
$attachmentNamestring|nullFile name shown to the user. If null, it will be determined from $filePath.
$optionsarrayAdditional 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

protected function defaultFormatters(): array

Returns

array: The formatters that are supported by default

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

ParameterTypeDescription
$dispositionstring
$attachmentNamestring

Returns

string

Since

2.0.10

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

Determines the HTTP range given in the request.

Parameters

ParameterTypeDescription
$fileSizeintThe 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.

protected function prepare(): mixed

Prepares for sending the response.

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

Returns

mixed

Throws

See also

protected function sendContent(): mixed

Sends the response content to the client.

Returns

mixed

protected function sendCookies(): mixed

Sends the cookies to the client.

Returns

mixed

protected function sendHeaders(): mixed

Sends the response headers to the client.

Returns

mixed