PHP Class yii\web\Response

It holds the [[headers]], [[cookies]] and [[content]] that is to be sent to the client. It also controls the HTTP [[statusCode|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: php 'response' => [ 'format' => yii\web\Response::FORMAT_JSON, 'charset' => 'UTF-8', ... ] For more details and usage information on Response, see the guide article on responses.
Since: 2.0
Author: Qiang Xue ([email protected])
Author: Carsten Brandt ([email protected])
Inheritance: extends yii\base\Response
Afficher le fichier Open project: yiisoft/yii2 Class Usage Examples

Méthodes publiques

Свойство Type Description
$acceptMimeType the MIME type (e.g. application/json) from the request ACCEPT header chosen for this response. This property is mainly set by ContentNegotiator.
$acceptParams the parameters (e.g. ['q' => 1, 'version' => '1.0']) associated with the [[acceptMimeType|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.
$charset the charset of the text response. If not set, it will use the value of [[Application::charset]].
$content the response content. When [[data]] is not null, it will be converted into [[content]] according to [[format]] when the response is being sent out.
$data 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.
$format 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]].
$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.
$httpStatuses list of HTTP status codes and the corresponding texts
$isSent whether the response has been sent. If this is true, calling Response::send will do nothing.
$statusText the HTTP status description that comes together with the status code.
$stream the stream to be sent. This can be a stream handle or an array of stream handle, the begin position and the end position. Note that when this property is set, the [[data]] and [[content]] properties will be ignored by Response::send.
$version 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.

Méthodes publiques

Méthode Description
clear ( ) Clears the headers, cookies, content, status code of the response.
getCookies ( ) : CookieCollection Returns the cookie collection.
getHeaders ( ) : HeaderCollection Returns the header collection.
getIsClientError ( ) : boolean
getIsEmpty ( ) : boolean
getIsForbidden ( ) : boolean
getIsInformational ( ) : boolean
getIsInvalid ( ) : boolean
getIsNotFound ( ) : boolean
getIsOk ( ) : boolean
getIsRedirection ( ) : boolean
getIsServerError ( ) : boolean
getIsSuccessful ( ) : boolean
getStatusCode ( ) : integer
init ( ) Initializes this component.
redirect ( string | array $url, integer $statusCode = 302, boolean $checkAjax = true ) Redirects the browser to the specified URL.
refresh ( string $anchor = '' ) : Response Refreshes the current page.
send ( ) Sends the response to the client.
sendContentAsFile ( string $content, string $attachmentName, array $options = [] ) Sends the specified content as a file to the browser.
sendFile ( string $filePath, string $attachmentName = null, array $options = [] ) Sends a file to the browser.
sendStreamAsFile ( resource $handle, string $attachmentName, array $options = [] ) Sends the specified stream as a file to the browser.
setDownloadHeaders ( string $attachmentName, string $mimeType = null, boolean $inline = false, integer $contentLength = null ) Sets a default set of HTTP headers for file downloading purpose.
setStatusCode ( integer $value, string $text = null ) Sets the response status code.
xSendFile ( string $filePath, string $attachmentName = null, array $options = [] ) Sends existing file to a browser as a download using x-sendfile.

Méthodes protégées

Méthode Description
defaultFormatters ( ) : array
getDispositionHeaderValue ( string $disposition, string $attachmentName ) : string Returns Content-Disposition header value that is safe to use with both old and new browsers
getHttpRange ( integer $fileSize ) : array | boolean Determines the HTTP range given in the request.
prepare ( ) Prepares for sending the response.
sendContent ( ) Sends the response content to the client
sendCookies ( ) Sends the cookies to the client.
sendHeaders ( ) Sends the response headers to the client

Method Details

clear() public méthode

Clears the headers, cookies, content, status code of the response.
public clear ( )

defaultFormatters() protected méthode

protected defaultFormatters ( ) : array
Résultat array the formatters that are supported by default

getCookies() public méthode

Through the returned cookie collection, you add or remove cookies as follows, php 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 getCookies ( ) : CookieCollection
Résultat CookieCollection the cookie collection.

getDispositionHeaderValue() protected méthode

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.
Since: 2.0.10
protected getDispositionHeaderValue ( string $disposition, string $attachmentName ) : string
$disposition string
$attachmentName string
Résultat string

getHeaders() public méthode

The header collection contains the currently registered HTTP headers.
public getHeaders ( ) : HeaderCollection
Résultat HeaderCollection the header collection

getHttpRange() protected méthode

Determines the HTTP range given in the request.
protected getHttpRange ( integer $fileSize ) : array | boolean
$fileSize integer the size of the file that will be used to validate the requested HTTP range.
Résultat array | boolean the range (begin, end), or false if the range request is invalid.

getIsClientError() public méthode

public getIsClientError ( ) : boolean
Résultat boolean whether this response indicates a client error

getIsEmpty() public méthode

public getIsEmpty ( ) : boolean
Résultat boolean whether this response is empty

getIsForbidden() public méthode

public getIsForbidden ( ) : boolean
Résultat boolean whether this response indicates the current request is forbidden

getIsInformational() public méthode

public getIsInformational ( ) : boolean
Résultat boolean whether this response is informational

getIsInvalid() public méthode

public getIsInvalid ( ) : boolean
Résultat boolean whether this response has a valid [[statusCode]].

getIsNotFound() public méthode

public getIsNotFound ( ) : boolean
Résultat boolean whether this response indicates the currently requested resource is not found

getIsOk() public méthode

public getIsOk ( ) : boolean
Résultat boolean whether this response is OK

getIsRedirection() public méthode

public getIsRedirection ( ) : boolean
Résultat boolean whether this response is a redirection

getIsServerError() public méthode

public getIsServerError ( ) : boolean
Résultat boolean whether this response indicates a server error

getIsSuccessful() public méthode

public getIsSuccessful ( ) : boolean
Résultat boolean whether this response is successful

getStatusCode() public méthode

public getStatusCode ( ) : integer
Résultat integer the HTTP status code to send with the response.

init() public méthode

Initializes this component.
public init ( )

prepare() protected méthode

The default implementation will convert [[data]] into [[content]] and set headers accordingly.
protected prepare ( )

redirect() public méthode

This method adds a "Location" header to the current response. Note that it does not send out the header until Response::send is called. In a controller action you may use this method as follows: php 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: php 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: javascript $document.ajaxComplete(function (event, xhr, settings) { var url = xhr.getResponseHeader('X-Redirect'); if (url) { window.location = url; } });
public redirect ( string | array $url, integer $statusCode = 302, boolean $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. [[Url::to()]] will be used to convert the array into a URL. Any relative URL 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 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.

refresh() public méthode

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: php return Yii::$app->getResponse()->refresh();
public refresh ( string $anchor = '' ) : Response
$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.
Résultat Response the response object itself

send() public méthode

Sends the response to the client.
public send ( )

sendContent() protected méthode

Sends the response content to the client
protected sendContent ( )

sendContentAsFile() public méthode

Note that this method only prepares the response for file sending. The file is not sent until Response::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 sendContentAsFile ( string $content, string $attachmentName, array $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.

sendCookies() protected méthode

Sends the cookies to the client.
protected sendCookies ( )

sendFile() public méthode

Note that this method only prepares the response for file sending. The file is not sent until Response::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: php 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()
See also: sendStreamAsFile()
See also: xSendFile()
public sendFile ( string $filePath, string $attachmentName = null, array $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.

sendHeaders() protected méthode

Sends the response headers to the client
protected sendHeaders ( )

sendStreamAsFile() public méthode

Note that this method only prepares the response for file sending. The file is not sent until Response::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 sendStreamAsFile ( resource $handle, string $attachmentName, array $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.

setDownloadHeaders() public méthode

Sets a default set of HTTP headers for file downloading purpose.
public setDownloadHeaders ( string $attachmentName, string $mimeType = null, boolean $inline = false, integer $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.

setStatusCode() public méthode

This method will set the corresponding status text if $text is null.
public setStatusCode ( integer $value, string $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.

xSendFile() public méthode

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** php Yii::$app->response->xSendFile('/home/user/Pictures/picture1.jpg');
See also: sendFile()
public xSendFile ( string $filePath, string $attachmentName = null, array $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".

Property Details

$acceptMimeType public_oe property

the MIME type (e.g. application/json) from the request ACCEPT header chosen for this response. This property is mainly set by ContentNegotiator.
public $acceptMimeType

$acceptParams public_oe property

the parameters (e.g. ['q' => 1, 'version' => '1.0']) associated with the [[acceptMimeType|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 $acceptParams

$charset public_oe property

the charset of the text response. If not set, it will use the value of [[Application::charset]].
public $charset

$content public_oe 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 $content

$data public_oe 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 $data

$format public_oe 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 XmlResponseFormatter for more details. You may customize the formatting process or support additional formats by configuring [[formatters]].
See also: formatters
public $format

$formatters public_oe 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
See also: defaultFormatters
public $formatters

$httpStatuses public_oe static_oe property

list of HTTP status codes and the corresponding texts
public static $httpStatuses

$isSent public_oe property

whether the response has been sent. If this is true, calling Response::send will do nothing.
public $isSent

$statusText public_oe property

the HTTP status description that comes together with the status code.
See also: httpStatuses
public $statusText

$stream public_oe 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. Note that when this property is set, the [[data]] and [[content]] properties will be ignored by Response::send.
public $stream

$version public_oe 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 $version