Class yii\web\Response

Inheritanceyii\web\Response » yii\base\Response » yii\base\Component » yii\base\BaseObject
Implementsyii\base\Configurable
Available since version2.0
Source Code https://github.com/yiisoft/yii2/blob/master/framework/web/Response.php

The web Response class represents an HTTP response.

It holds the $headers, $cookies and $content that is to be sent to the client. It also controls the HTTP status code.

Response is configured as an application component in yii\web\Application by default. You can access that instance via Yii::$app->response.

You can modify its configuration by adding an array to your application config under components as it is shown in the following example:

'response' => [
    'format' => yii\web\Response::FORMAT_JSON,
    'charset' => 'UTF-8',
    // ...
]

For more details and usage information on Response, see the guide article on responses.

Public Properties

Hide inherited properties

Property Type Description Defined By
$acceptMimeType string The MIME type (e.g. application/json) from the request ACCEPT header chosen for this response. yii\web\Response
$acceptParams array The parameters (e.g. ['q' => 1, 'version' => '1.0']) associated with the chosen MIME type. yii\web\Response
$behaviors yii\base\Behavior[] List of behaviors attached to this component. yii\base\Component
$charset string|null The charset of the text response. yii\web\Response
$content string|null The response content. yii\web\Response
$cookies yii\web\CookieCollection The cookie collection. yii\web\Response
$data mixed The original response data. yii\web\Response
$downloadHeaders string The attachment file name. yii\web\Response
$exitStatus integer The exit status. yii\base\Response
$format string The response format. yii\web\Response
$formatters array The formatters for converting data into the response content of the specified $format. yii\web\Response
$headers yii\web\HeaderCollection The header collection. yii\web\Response
$httpStatuses array List of HTTP status codes and the corresponding texts yii\web\Response
$isClientError boolean Whether this response indicates a client error. yii\web\Response
$isEmpty boolean Whether this response is empty. yii\web\Response
$isForbidden boolean Whether this response indicates the current request is forbidden. yii\web\Response
$isInformational boolean Whether this response is informational. yii\web\Response
$isInvalid boolean Whether this response has a valid $statusCode. yii\web\Response
$isNotFound boolean Whether this response indicates the currently requested resource is not found. yii\web\Response
$isOk boolean Whether this response is OK. yii\web\Response
$isRedirection boolean Whether this response is a redirection. yii\web\Response
$isSent boolean Whether the response has been sent. yii\web\Response
$isServerError boolean Whether this response indicates a server error. yii\web\Response
$isSuccessful boolean Whether this response is successful. yii\web\Response
$statusCode integer The HTTP status code to send with the response. yii\web\Response
$statusCodeByException Throwable The exception object. yii\web\Response
$statusText string The HTTP status description that comes together with the status code. yii\web\Response
$stream resource|array|callable The stream to be sent. yii\web\Response
$version string|null The version of the HTTP protocol to use. yii\web\Response

Public Methods

Hide inherited methods

Method Description Defined By
__call() Calls the named method which is not a class method. yii\base\Component
__clone() This method is called after the object is created by cloning an existing one. yii\base\Component
__construct() Constructor. yii\base\BaseObject
__get() Returns the value of a component property. yii\base\Component
__isset() Checks if a property is set, i.e. defined and not null. yii\base\Component
__set() Sets the value of a component property. yii\base\Component
__unset() Sets a component property to be null. yii\base\Component
attachBehavior() Attaches a behavior to this component. yii\base\Component
attachBehaviors() Attaches a list of behaviors to the component. yii\base\Component
behaviors() Returns a list of behaviors that this component should behave as. yii\base\Component
canGetProperty() Returns a value indicating whether a property can be read. yii\base\Component
canSetProperty() Returns a value indicating whether a property can be set. yii\base\Component
className() Returns the fully qualified name of this class. yii\base\BaseObject
clear() Clears the headers, cookies, content, status code of the response. yii\web\Response
clearOutputBuffers() Removes all existing output buffers. yii\base\Response
detachBehavior() Detaches a behavior from the component. yii\base\Component
detachBehaviors() Detaches all behaviors from the component. yii\base\Component
ensureBehaviors() Makes sure that the behaviors declared in behaviors() are attached to this component. yii\base\Component
getBehavior() Returns the named behavior object. yii\base\Component
getBehaviors() Returns all behaviors attached to this component. yii\base\Component
getCookies() Returns the cookie collection. yii\web\Response
getHeaders() Returns the header collection. yii\web\Response
getIsClientError() yii\web\Response
getIsEmpty() yii\web\Response
getIsForbidden() yii\web\Response
getIsInformational() yii\web\Response
getIsInvalid() yii\web\Response
getIsNotFound() yii\web\Response
getIsOk() yii\web\Response
getIsRedirection() yii\web\Response
getIsServerError() yii\web\Response
getIsSuccessful() yii\web\Response
getStatusCode() yii\web\Response
hasEventHandlers() Returns a value indicating whether there is any handler attached to the named event. yii\base\Component
hasMethod() Returns a value indicating whether a method is defined. yii\base\Component
hasProperty() Returns a value indicating whether a property is defined for this component. yii\base\Component
init() Initializes this component. yii\web\Response
off() Detaches an existing event handler from this component. yii\base\Component
on() Attaches an event handler to an event. yii\base\Component
redirect() Redirects the browser to the specified URL. yii\web\Response
refresh() Refreshes the current page. yii\web\Response
send() Sends the response to the client. yii\web\Response
sendContentAsFile() Sends the specified content as a file to the browser. yii\web\Response
sendFile() Sends a file to the browser. yii\web\Response
sendStreamAsFile() Sends the specified stream as a file to the browser. yii\web\Response
setDownloadHeaders() Sets a default set of HTTP headers for file downloading purpose. yii\web\Response
setStatusCode() Sets the response status code. yii\web\Response
setStatusCodeByException() Sets the response status code based on the exception. yii\web\Response
trigger() Triggers an event. yii\base\Component
xSendFile() Sends existing file to a browser as a download using x-sendfile. yii\web\Response

Protected Methods

Hide inherited methods

Method Description Defined By
defaultFormatters() yii\web\Response
getDispositionHeaderValue() Returns Content-Disposition header value that is safe to use with both old and new browsers. yii\web\Response
getHttpRange() Determines the HTTP range given in the request. yii\web\Response
prepare() Prepares for sending the response. yii\web\Response
sendContent() Sends the response content to the client. yii\web\Response
sendCookies() Sends the cookies to the client. yii\web\Response
sendHeaders() Sends the response headers to the client. yii\web\Response

Events

Hide inherited events

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

Constants

Hide inherited constants

Constant Value Description Defined By
FORMAT_HTML 'html' yii\web\Response
FORMAT_JSON 'json' yii\web\Response
FORMAT_JSONP 'jsonp' yii\web\Response
FORMAT_RAW 'raw' yii\web\Response
FORMAT_XML 'xml' yii\web\Response

Property Details

Hide inherited properties

$acceptMimeType public property

The MIME type (e.g. application/json) from the request ACCEPT header chosen for this response. This property is mainly set by yii\filters\ContentNegotiator.

public string $acceptMimeType null
$acceptParams public property

The parameters (e.g. ['q' => 1, 'version' => '1.0']) associated with the chosen MIME type. This is a list of name-value pairs associated with $acceptMimeType from the ACCEPT HTTP header. This property is mainly set by yii\filters\ContentNegotiator.

public array $acceptParams = []
$charset public property

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

public string|null $charset null
$content public property

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

See also $data.

public string|null $content null
$cookies public property

The cookie collection.

$data public property

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

See also $content.

public mixed $data null
$downloadHeaders public property

The attachment file name.

public string $downloadHeaders null
$format public property

The response format. This determines how to convert $data into $content when the latter is not set. The value of this property must be one of the keys declared in the $formatters array. By default, the following formats are supported:

  • FORMAT_RAW: the data will be treated as the response content without any conversion. No extra HTTP header will be added.
  • FORMAT_HTML: the data will be treated as the response content without any conversion. The "Content-Type" header will set as "text/html".
  • FORMAT_JSON: the data will be converted into JSON format, and the "Content-Type" header will be set as "application/json".
  • FORMAT_JSONP: the data will be converted into JSONP format, and the "Content-Type" header will be set as "text/javascript". Note that in this case $data must be an array with "data" and "callback" elements. The former refers to the actual data to be sent, while the latter refers to the name of the JavaScript callback.
  • FORMAT_XML: the data will be converted into XML format. Please refer to yii\web\XmlResponseFormatter for more details.

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

See also $formatters.

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

The formatters for converting data into the response content of the specified $format. The array keys are the format names, and the array values are the corresponding configurations for creating the formatter objects.

See also:

public array $formatters = []
$headers public property

The header collection.

$httpStatuses public static property

List of HTTP status codes and the corresponding texts

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

Whether this response indicates a client error.

public boolean $isClientError null
$isEmpty public property

Whether this response is empty.

public boolean $isEmpty null
$isForbidden public property

Whether this response indicates the current request is forbidden.

public boolean $isForbidden null
$isInformational public property

Whether this response is informational.

public boolean $isInformational null
$isInvalid public property

Whether this response has a valid $statusCode.

public boolean $isInvalid null
$isNotFound public property

Whether this response indicates the currently requested resource is not found.

public boolean $isNotFound null
$isOk public property

Whether this response is OK.

public boolean $isOk null
$isRedirection public property

Whether this response is a redirection.

public boolean $isRedirection null
$isSent public property

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

public boolean $isSent false
$isServerError public property

Whether this response indicates a server error.

public boolean $isServerError null
$isSuccessful public property

Whether this response is successful.

public boolean $isSuccessful null
$statusCode public property

The HTTP status code to send with the response.

public integer $statusCode null
$statusCodeByException public property

The exception object.

$statusText public property

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

See also $httpStatuses.

public string $statusText 'OK'
$stream public property

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

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

$version public property

The version of the HTTP protocol to use. If not set, it will be determined via $_SERVER['SERVER_PROTOCOL'], or '1.1' if that is not available.

public string|null $version null

Method Details

Hide inherited methods

__call() public method

Defined in: yii\base\Component::__call()

Calls the named method which is not a class method.

This method will check if any attached behavior has the named method and will execute it if available.

Do not call this method directly as it is a PHP magic method that will be implicitly called when an unknown method is being invoked.

public mixed __call ( $name, $params )
$name string

The method name

$params array

Method parameters

return mixed

The method return value

throws yii\base\UnknownMethodException

when calling unknown method

                public function __call($name, $params)
{
    $this->ensureBehaviors();
    foreach ($this->_behaviors as $object) {
        if ($object->hasMethod($name)) {
            return call_user_func_array([$object, $name], $params);
        }
    }
    throw new UnknownMethodException('Calling unknown method: ' . get_class($this) . "::$name()");
}

            
__clone() public method

Defined in: yii\base\Component::__clone()

This method is called after the object is created by cloning an existing one.

It removes all behaviors because they are attached to the old object.

public void __clone ( )

                public function __clone()
{
    $this->_events = [];
    $this->_eventWildcards = [];
    $this->_behaviors = null;
}

            
__construct() public method

Defined in: yii\base\BaseObject::__construct()

Constructor.

The default implementation does two things:

  • Initializes the object with the given configuration $config.
  • Call init().

If this method is overridden in a child class, it is recommended that

  • the last parameter of the constructor is a configuration array, like $config here.
  • call the parent implementation at the end of the constructor.
public void __construct ( $config = [] )
$config array

Name-value pairs that will be used to initialize the object properties

                public function __construct($config = [])
{
    if (!empty($config)) {
        Yii::configure($this, $config);
    }
    $this->init();
}

            
__get() public method

Defined in: yii\base\Component::__get()

Returns the value of a component property.

This method will check in the following order and act accordingly:

  • a property defined by a getter: return the getter result
  • a property of a behavior: return the behavior property value

Do not call this method directly as it is a PHP magic method that will be implicitly called when executing $value = $component->property;.

See also __set().

public mixed __get ( $name )
$name string

The property name

return mixed

The property value or the value of a behavior's property

throws yii\base\UnknownPropertyException

if the property is not defined

throws yii\base\InvalidCallException

if the property is write-only.

                public function __get($name)
{
    $getter = 'get' . $name;
    if (method_exists($this, $getter)) {
        // read property, e.g. getName()
        return $this->$getter();
    }
    // behavior property
    $this->ensureBehaviors();
    foreach ($this->_behaviors as $behavior) {
        if ($behavior->canGetProperty($name)) {
            return $behavior->$name;
        }
    }
    if (method_exists($this, 'set' . $name)) {
        throw new InvalidCallException('Getting write-only property: ' . get_class($this) . '::' . $name);
    }
    throw new UnknownPropertyException('Getting unknown property: ' . get_class($this) . '::' . $name);
}

            
__isset() public method

Defined in: yii\base\Component::__isset()

Checks if a property is set, i.e. defined and not null.

This method will check in the following order and act accordingly:

  • a property defined by a setter: return whether the property is set
  • a property of a behavior: return whether the property is set
  • return false for non existing properties

Do not call this method directly as it is a PHP magic method that will be implicitly called when executing isset($component->property).

See also https://www.php.net/manual/en/function.isset.php.

public boolean __isset ( $name )
$name string

The property name or the event name

return boolean

Whether the named property is set

                public function __isset($name)
{
    $getter = 'get' . $name;
    if (method_exists($this, $getter)) {
        return $this->$getter() !== null;
    }
    // behavior property
    $this->ensureBehaviors();
    foreach ($this->_behaviors as $behavior) {
        if ($behavior->canGetProperty($name)) {
            return $behavior->$name !== null;
        }
    }
    return false;
}

            
__set() public method

Defined in: yii\base\Component::__set()

Sets the value of a component property.

This method will check in the following order and act accordingly:

  • a property defined by a setter: set the property value
  • an event in the format of "on xyz": attach the handler to the event "xyz"
  • a behavior in the format of "as xyz": attach the behavior named as "xyz"
  • a property of a behavior: set the behavior property value

Do not call this method directly as it is a PHP magic method that will be implicitly called when executing $component->property = $value;.

See also __get().

public void __set ( $name, $value )
$name string

The property name or the event name

$value mixed

The property value

throws yii\base\UnknownPropertyException

if the property is not defined

throws yii\base\InvalidCallException

if the property is read-only.

                public function __set($name, $value)
{
    $setter = 'set' . $name;
    if (method_exists($this, $setter)) {
        // set property
        $this->$setter($value);
        return;
    } elseif (strncmp($name, 'on ', 3) === 0) {
        // on event: attach event handler
        $this->on(trim(substr($name, 3)), $value);
        return;
    } elseif (strncmp($name, 'as ', 3) === 0) {
        // as behavior: attach behavior
        $name = trim(substr($name, 3));
        $this->attachBehavior($name, $value instanceof Behavior ? $value : Yii::createObject($value));
        return;
    }
    // behavior property
    $this->ensureBehaviors();
    foreach ($this->_behaviors as $behavior) {
        if ($behavior->canSetProperty($name)) {
            $behavior->$name = $value;
            return;
        }
    }
    if (method_exists($this, 'get' . $name)) {
        throw new InvalidCallException('Setting read-only property: ' . get_class($this) . '::' . $name);
    }
    throw new UnknownPropertyException('Setting unknown property: ' . get_class($this) . '::' . $name);
}

            
__unset() public method

Defined in: yii\base\Component::__unset()

Sets a component property to be null.

This method will check in the following order and act accordingly:

  • a property defined by a setter: set the property value to be null
  • a property of a behavior: set the property value to be null

Do not call this method directly as it is a PHP magic method that will be implicitly called when executing unset($component->property).

See also https://www.php.net/manual/en/function.unset.php.

public void __unset ( $name )
$name string

The property name

throws yii\base\InvalidCallException

if the property is read only.

                public function __unset($name)
{
    $setter = 'set' . $name;
    if (method_exists($this, $setter)) {
        $this->$setter(null);
        return;
    }
    // behavior property
    $this->ensureBehaviors();
    foreach ($this->_behaviors as $behavior) {
        if ($behavior->canSetProperty($name)) {
            $behavior->$name = null;
            return;
        }
    }
    throw new InvalidCallException('Unsetting an unknown or read-only property: ' . get_class($this) . '::' . $name);
}

            
attachBehavior() public method

Defined in: yii\base\Component::attachBehavior()

Attaches a behavior to this component.

This method will create the behavior object based on the given configuration. After that, the behavior object will be attached to this component by calling the yii\base\Behavior::attach() method.

See also detachBehavior().

public yii\base\Behavior attachBehavior ( $name, $behavior )
$name string

The name of the behavior.

$behavior string|array|yii\base\Behavior

The behavior configuration. This can be one of the following:

return yii\base\Behavior

The behavior object

                public function attachBehavior($name, $behavior)
{
    $this->ensureBehaviors();
    return $this->attachBehaviorInternal($name, $behavior);
}

            
attachBehaviors() public method

Defined in: yii\base\Component::attachBehaviors()

Attaches a list of behaviors to the component.

Each behavior is indexed by its name and should be a yii\base\Behavior object, a string specifying the behavior class, or an configuration array for creating the behavior.

See also attachBehavior().

public void attachBehaviors ( $behaviors )
$behaviors array

List of behaviors to be attached to the component

                public function attachBehaviors($behaviors)
{
    $this->ensureBehaviors();
    foreach ($behaviors as $name => $behavior) {
        $this->attachBehaviorInternal($name, $behavior);
    }
}

            
behaviors() public method

Defined in: yii\base\Component::behaviors()

Returns a list of behaviors that this component should behave as.

Child classes may override this method to specify the behaviors they want to behave as.

The return value of this method should be an array of behavior objects or configurations indexed by behavior names. A behavior configuration can be either a string specifying the behavior class or an array of the following structure:

'behaviorName' => [
    'class' => 'BehaviorClass',
    'property1' => 'value1',
    'property2' => 'value2',
]

Note that a behavior class must extend from yii\base\Behavior. Behaviors can be attached using a name or anonymously. When a name is used as the array key, using this name, the behavior can later be retrieved using getBehavior() or be detached using detachBehavior(). Anonymous behaviors can not be retrieved or detached.

Behaviors declared in this method will be attached to the component automatically (on demand).

public array behaviors ( )
return array

The behavior configurations.

                public function behaviors()
{
    return [];
}

            
canGetProperty() public method

Defined in: yii\base\Component::canGetProperty()

Returns a value indicating whether a property can be read.

A property can be read if:

  • the class has a getter method associated with the specified name (in this case, property name is case-insensitive);
  • the class has a member variable with the specified name (when $checkVars is true);
  • an attached behavior has a readable property of the given name (when $checkBehaviors is true).

See also canSetProperty().

public boolean canGetProperty ( $name, $checkVars true, $checkBehaviors true )
$name string

The property name

$checkVars boolean

Whether to treat member variables as properties

$checkBehaviors boolean

Whether to treat behaviors' properties as properties of this component

return boolean

Whether the property can be read

                public function canGetProperty($name, $checkVars = true, $checkBehaviors = true)
{
    if (method_exists($this, 'get' . $name) || $checkVars && property_exists($this, $name)) {
        return true;
    } elseif ($checkBehaviors) {
        $this->ensureBehaviors();
        foreach ($this->_behaviors as $behavior) {
            if ($behavior->canGetProperty($name, $checkVars)) {
                return true;
            }
        }
    }
    return false;
}

            
canSetProperty() public method

Defined in: yii\base\Component::canSetProperty()

Returns a value indicating whether a property can be set.

A property can be written if:

  • the class has a setter method associated with the specified name (in this case, property name is case-insensitive);
  • the class has a member variable with the specified name (when $checkVars is true);
  • an attached behavior has a writable property of the given name (when $checkBehaviors is true).

See also canGetProperty().

public boolean canSetProperty ( $name, $checkVars true, $checkBehaviors true )
$name string

The property name

$checkVars boolean

Whether to treat member variables as properties

$checkBehaviors boolean

Whether to treat behaviors' properties as properties of this component

return boolean

Whether the property can be written

                public function canSetProperty($name, $checkVars = true, $checkBehaviors = true)
{
    if (method_exists($this, 'set' . $name) || $checkVars && property_exists($this, $name)) {
        return true;
    } elseif ($checkBehaviors) {
        $this->ensureBehaviors();
        foreach ($this->_behaviors as $behavior) {
            if ($behavior->canSetProperty($name, $checkVars)) {
                return true;
            }
        }
    }
    return false;
}

            
className() public static method
Deprecated since 2.0.14. On PHP >=5.5, use ::class instead.

Defined in: yii\base\BaseObject::className()

Returns the fully qualified name of this class.

public static string className ( )
return string

The fully qualified name of this class.

                public static function className()
{
    return get_called_class();
}

            
clear() public method

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

public void clear ( )

                public function clear()
{
    $this->_headers = null;
    $this->_cookies = null;
    $this->_statusCode = 200;
    $this->statusText = 'OK';
    $this->data = null;
    $this->stream = null;
    $this->content = null;
    $this->isSent = false;
}

            
clearOutputBuffers() public method

Defined in: yii\base\Response::clearOutputBuffers()

Removes all existing output buffers.

public void clearOutputBuffers ( )

                public function clearOutputBuffers()
{
    // the following manual level counting is to deal with zlib.output_compression set to On
    for ($level = ob_get_level(); $level > 0; --$level) {
        if (!@ob_end_clean()) {
            ob_clean();
        }
    }
}

            
defaultFormatters() protected method

protected array defaultFormatters ( )
return array

The formatters that are supported by default

                protected function defaultFormatters()
{
    return [
        self::FORMAT_HTML => [
            'class' => 'yii\web\HtmlResponseFormatter',
        ],
        self::FORMAT_XML => [
            'class' => 'yii\web\XmlResponseFormatter',
        ],
        self::FORMAT_JSON => [
            'class' => 'yii\web\JsonResponseFormatter',
        ],
        self::FORMAT_JSONP => [
            'class' => 'yii\web\JsonResponseFormatter',
            'useJsonp' => true,
        ],
    ];
}

            
detachBehavior() public method

Defined in: yii\base\Component::detachBehavior()

Detaches a behavior from the component.

The behavior's yii\base\Behavior::detach() method will be invoked.

public yii\base\Behavior|null detachBehavior ( $name )
$name string

The behavior's name.

return yii\base\Behavior|null

The detached behavior. Null if the behavior does not exist.

                public function detachBehavior($name)
{
    $this->ensureBehaviors();
    if (isset($this->_behaviors[$name])) {
        $behavior = $this->_behaviors[$name];
        unset($this->_behaviors[$name]);
        $behavior->detach();
        return $behavior;
    }
    return null;
}

            
detachBehaviors() public method

Defined in: yii\base\Component::detachBehaviors()

Detaches all behaviors from the component.

public void detachBehaviors ( )

                public function detachBehaviors()
{
    $this->ensureBehaviors();
    foreach ($this->_behaviors as $name => $behavior) {
        $this->detachBehavior($name);
    }
}

            
ensureBehaviors() public method

Defined in: yii\base\Component::ensureBehaviors()

Makes sure that the behaviors declared in behaviors() are attached to this component.

public void ensureBehaviors ( )

                public function ensureBehaviors()
{
    if ($this->_behaviors === null) {
        $this->_behaviors = [];
        foreach ($this->behaviors() as $name => $behavior) {
            $this->attachBehaviorInternal($name, $behavior);
        }
    }
}

            
getBehavior() public method

Defined in: yii\base\Component::getBehavior()

Returns the named behavior object.

public yii\base\Behavior|null getBehavior ( $name )
$name string

The behavior name

return yii\base\Behavior|null

The behavior object, or null if the behavior does not exist

                public function getBehavior($name)
{
    $this->ensureBehaviors();
    return isset($this->_behaviors[$name]) ? $this->_behaviors[$name] : null;
}

            
getBehaviors() public method

Defined in: yii\base\Component::getBehaviors()

Returns all behaviors attached to this component.

public yii\base\Behavior[] getBehaviors ( )
return yii\base\Behavior[]

List of behaviors attached to this component

                public function getBehaviors()
{
    $this->ensureBehaviors();
    return $this->_behaviors;
}

            
getCookies() public method

Returns the cookie collection.

Through the returned cookie collection, you add or remove cookies as follows,

// add a cookie
$response->cookies->add(new Cookie([
    'name' => $name,
    'value' => $value,
]);

// remove a cookie
$response->cookies->remove('name');
// alternatively
unset($response->cookies['name']);
public yii\web\CookieCollection getCookies ( )
return yii\web\CookieCollection

The cookie collection.

                public function getCookies()
{
    if ($this->_cookies === null) {
        $this->_cookies = new CookieCollection();
    }
    return $this->_cookies;
}

            
getDispositionHeaderValue() protected method (available since version 2.0.10)

Returns Content-Disposition header value that is safe to use with both old and new browsers.

Fallback name:

  • Causes issues if contains non-ASCII characters with codes less than 32 or more than 126.
  • Causes issues if contains urlencoded characters (starting with %) or % character. Some browsers interpret filename="X" as urlencoded name, some don't.
  • Causes issues if contains path separator characters such as \ or /.
  • Since value is wrapped with ", it should be escaped as \".
  • Since input could contain non-ASCII characters, fallback is obtained by transliteration.

UTF name:

  • Causes issues if contains path separator characters such as \ or /.
  • Should be urlencoded since headers are ASCII-only.
  • Could be omitted if it exactly matches fallback name.
protected string getDispositionHeaderValue ( $disposition, $attachmentName )
$disposition string
$attachmentName string

                protected function getDispositionHeaderValue($disposition, $attachmentName)
{
    $fallbackName = str_replace(
        ['%', '/', '\\', '"', "\x7F"],
        ['_', '_', '_', '\\"', '_'],
        Inflector::transliterate($attachmentName, Inflector::TRANSLITERATE_LOOSE)
    );
    $utfName = rawurlencode(str_replace(['%', '/', '\\'], '', $attachmentName));
    $dispositionHeader = "{$disposition}; filename=\"{$fallbackName}\"";
    if ($utfName !== $fallbackName) {
        $dispositionHeader .= "; filename*=utf-8''{$utfName}";
    }
    return $dispositionHeader;
}

            
getHeaders() public method

Returns the header collection.

The header collection contains the currently registered HTTP headers.

public yii\web\HeaderCollection getHeaders ( )
return yii\web\HeaderCollection

The header collection

                public function getHeaders()
{
    if ($this->_headers === null) {
        $this->_headers = new HeaderCollection();
    }
    return $this->_headers;
}

            
getHttpRange() protected method

Determines the HTTP range given in the request.

protected array|boolean getHttpRange ( $fileSize )
$fileSize integer

The size of the file that will be used to validate the requested HTTP range.

return array|boolean

The range (begin, end), or false if the range request is invalid.

                protected function getHttpRange($fileSize)
{
    $rangeHeader = Yii::$app->getRequest()->getHeaders()->get('Range', '-');
    if ($rangeHeader === '-') {
        return [0, $fileSize - 1];
    }
    if (!preg_match('/^bytes=(\d*)-(\d*)$/', $rangeHeader, $matches)) {
        return false;
    }
    if ($matches[1] === '') {
        $start = $fileSize - $matches[2];
        $end = $fileSize - 1;
    } elseif ($matches[2] !== '') {
        $start = $matches[1];
        $end = $matches[2];
        if ($end >= $fileSize) {
            $end = $fileSize - 1;
        }
    } else {
        $start = $matches[1];
        $end = $fileSize - 1;
    }
    if ($start < 0 || $start > $end) {
        return false;
    }
    return [$start, $end];
}

            
getIsClientError() public method

public boolean getIsClientError ( )
return boolean

Whether this response indicates a client error

                public function getIsClientError()
{
    return $this->getStatusCode() >= 400 && $this->getStatusCode() < 500;
}

            
getIsEmpty() public method

public boolean getIsEmpty ( )
return boolean

Whether this response is empty

                public function getIsEmpty()
{
    return in_array($this->getStatusCode(), [201, 204, 304]);
}

            
getIsForbidden() public method

public boolean getIsForbidden ( )
return boolean

Whether this response indicates the current request is forbidden

                public function getIsForbidden()
{
    return $this->getStatusCode() == 403;
}

            
getIsInformational() public method

public boolean getIsInformational ( )
return boolean

Whether this response is informational

                public function getIsInformational()
{
    return $this->getStatusCode() >= 100 && $this->getStatusCode() < 200;
}

            
getIsInvalid() public method

public boolean getIsInvalid ( )
return boolean

Whether this response has a valid $statusCode.

                public function getIsInvalid()
{
    return $this->getStatusCode() < 100 || $this->getStatusCode() >= 600;
}

            
getIsNotFound() public method

public boolean getIsNotFound ( )
return boolean

Whether this response indicates the currently requested resource is not found

                public function getIsNotFound()
{
    return $this->getStatusCode() == 404;
}

            
getIsOk() public method

public boolean getIsOk ( )
return boolean

Whether this response is OK

                public function getIsOk()
{
    return $this->getStatusCode() == 200;
}

            
getIsRedirection() public method

public boolean getIsRedirection ( )
return boolean

Whether this response is a redirection

                public function getIsRedirection()
{
    return $this->getStatusCode() >= 300 && $this->getStatusCode() < 400;
}

            
getIsServerError() public method

public boolean getIsServerError ( )
return boolean

Whether this response indicates a server error

                public function getIsServerError()
{
    return $this->getStatusCode() >= 500 && $this->getStatusCode() < 600;
}

            
getIsSuccessful() public method

public boolean getIsSuccessful ( )
return boolean

Whether this response is successful

                public function getIsSuccessful()
{
    return $this->getStatusCode() >= 200 && $this->getStatusCode() < 300;
}

            
getStatusCode() public method

public integer getStatusCode ( )
return integer

The HTTP status code to send with the response.

                public function getStatusCode()
{
    return $this->_statusCode;
}

            
hasEventHandlers() public method

Defined in: yii\base\Component::hasEventHandlers()

Returns a value indicating whether there is any handler attached to the named event.

public boolean hasEventHandlers ( $name )
$name string

The event name

return boolean

Whether there is any handler attached to the event.

                public function hasEventHandlers($name)
{
    $this->ensureBehaviors();
    if (!empty($this->_events[$name])) {
        return true;
    }
    foreach ($this->_eventWildcards as $wildcard => $handlers) {
        if (!empty($handlers) && StringHelper::matchWildcard($wildcard, $name)) {
            return true;
        }
    }
    return Event::hasHandlers($this, $name);
}

            
hasMethod() public method

Defined in: yii\base\Component::hasMethod()

Returns a value indicating whether a method is defined.

A method is defined if:

  • the class has a method with the specified name
  • an attached behavior has a method with the given name (when $checkBehaviors is true).
public boolean hasMethod ( $name, $checkBehaviors true )
$name string

The property name

$checkBehaviors boolean

Whether to treat behaviors' methods as methods of this component

return boolean

Whether the method is defined

                public function hasMethod($name, $checkBehaviors = true)
{
    if (method_exists($this, $name)) {
        return true;
    } elseif ($checkBehaviors) {
        $this->ensureBehaviors();
        foreach ($this->_behaviors as $behavior) {
            if ($behavior->hasMethod($name)) {
                return true;
            }
        }
    }
    return false;
}

            
hasProperty() public method

Defined in: yii\base\Component::hasProperty()

Returns a value indicating whether a property is defined for this component.

A property is defined if:

  • the class has a getter or setter method associated with the specified name (in this case, property name is case-insensitive);
  • the class has a member variable with the specified name (when $checkVars is true);
  • an attached behavior has a property of the given name (when $checkBehaviors is true).

See also:

public boolean hasProperty ( $name, $checkVars true, $checkBehaviors true )
$name string

The property name

$checkVars boolean

Whether to treat member variables as properties

$checkBehaviors boolean

Whether to treat behaviors' properties as properties of this component

return boolean

Whether the property is defined

                public function hasProperty($name, $checkVars = true, $checkBehaviors = true)
{
    return $this->canGetProperty($name, $checkVars, $checkBehaviors) || $this->canSetProperty($name, false, $checkBehaviors);
}

            
init() public method

Initializes this component.

public void init ( )

                public function init()
{
    if ($this->version === null) {
        if (isset($_SERVER['SERVER_PROTOCOL']) && $_SERVER['SERVER_PROTOCOL'] === 'HTTP/1.0') {
            $this->version = '1.0';
        } else {
            $this->version = '1.1';
        }
    }
    if ($this->charset === null) {
        $this->charset = Yii::$app->charset;
    }
    $this->formatters = array_merge($this->defaultFormatters(), $this->formatters);
}

            
off() public method

Defined in: yii\base\Component::off()

Detaches an existing event handler from this component.

This method is the opposite of on().

Note: in case wildcard pattern is passed for event name, only the handlers registered with this wildcard will be removed, while handlers registered with plain names matching this wildcard will remain.

See also on().

public boolean off ( $name, $handler null )
$name string

Event name

$handler callable|null

The event handler to be removed. If it is null, all handlers attached to the named event will be removed.

return boolean

If a handler is found and detached

                public function off($name, $handler = null)
{
    $this->ensureBehaviors();
    if (empty($this->_events[$name]) && empty($this->_eventWildcards[$name])) {
        return false;
    }
    if ($handler === null) {
        unset($this->_events[$name], $this->_eventWildcards[$name]);
        return true;
    }
    $removed = false;
    // plain event names
    if (isset($this->_events[$name])) {
        foreach ($this->_events[$name] as $i => $event) {
            if ($event[0] === $handler) {
                unset($this->_events[$name][$i]);
                $removed = true;
            }
        }
        if ($removed) {
            $this->_events[$name] = array_values($this->_events[$name]);
            return true;
        }
    }
    // wildcard event names
    if (isset($this->_eventWildcards[$name])) {
        foreach ($this->_eventWildcards[$name] as $i => $event) {
            if ($event[0] === $handler) {
                unset($this->_eventWildcards[$name][$i]);
                $removed = true;
            }
        }
        if ($removed) {
            $this->_eventWildcards[$name] = array_values($this->_eventWildcards[$name]);
            // remove empty wildcards to save future redundant regex checks:
            if (empty($this->_eventWildcards[$name])) {
                unset($this->_eventWildcards[$name]);
            }
        }
    }
    return $removed;
}

            
on() public method

Defined in: yii\base\Component::on()

Attaches an event handler to an event.

The event handler must be a valid PHP callback. The following are some examples:

function ($event) { ... }         // anonymous function
[$object, 'handleClick']          // $object->handleClick()
['Page', 'handleClick']           // Page::handleClick()
'handleClick'                     // global function handleClick()

The event handler must be defined with the following signature,

function ($event)

where $event is an yii\base\Event object which includes parameters associated with the event.

Since 2.0.14 you can specify event name as a wildcard pattern:

$component->on('event.group.*', function ($event) {
    Yii::trace($event->name . ' is triggered.');
});

See also off().

public void on ( $name, $handler, $data null, $append true )
$name string

The event name

$handler callable

The event handler

$data mixed

The data to be passed to the event handler when the event is triggered. When the event handler is invoked, this data can be accessed via yii\base\Event::$data.

$append boolean

Whether to append new event handler to the end of the existing handler list. If false, the new handler will be inserted at the beginning of the existing handler list.

                public function on($name, $handler, $data = null, $append = true)
{
    $this->ensureBehaviors();
    if (strpos($name, '*') !== false) {
        if ($append || empty($this->_eventWildcards[$name])) {
            $this->_eventWildcards[$name][] = [$handler, $data];
        } else {
            array_unshift($this->_eventWildcards[$name], [$handler, $data]);
        }
        return;
    }
    if ($append || empty($this->_events[$name])) {
        $this->_events[$name][] = [$handler, $data];
    } else {
        array_unshift($this->_events[$name], [$handler, $data]);
    }
}

            
prepare() protected method

Prepares for sending the response.

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

See also:

protected void prepare ( )
throws yii\base\InvalidConfigException

if the formatter for the specified format is invalid or $format is not supported

                protected function prepare()
{
    if (in_array($this->getStatusCode(), [204, 304])) {
        // A 204/304 response cannot contain a message body according to rfc7231/rfc7232
        $this->content = '';
        $this->stream = null;
        return;
    }
    if ($this->stream !== null) {
        return;
    }
    if (isset($this->formatters[$this->format])) {
        $formatter = $this->formatters[$this->format];
        if (!is_object($formatter)) {
            $this->formatters[$this->format] = $formatter = Yii::createObject($formatter);
        }
        if ($formatter instanceof ResponseFormatterInterface) {
            $formatter->format($this);
        } else {
            throw new InvalidConfigException("The '{$this->format}' response formatter is invalid. It must implement the ResponseFormatterInterface.");
        }
    } elseif ($this->format === self::FORMAT_RAW) {
        if ($this->data !== null) {
            $this->content = $this->data;
        }
    } else {
        throw new InvalidConfigException("Unsupported response format: {$this->format}");
    }
    if (is_array($this->content)) {
        throw new InvalidArgumentException('Response content must not be an array.');
    } elseif (is_object($this->content)) {
        if (method_exists($this->content, '__toString')) {
            $this->content = $this->content->__toString();
        } else {
            throw new InvalidArgumentException('Response content must be a string or an object implementing __toString().');
        }
    }
}

            
redirect() public method

Redirects the browser to the specified URL.

This method adds a "Location" header to the current response. Note that it does not send out the header until send() is called. In a controller action you may use this method as follows:

return Yii::$app->getResponse()->redirect($url);

In other places, if you want to send out the "Location" header immediately, you should use the following code:

Yii::$app->getResponse()->redirect($url)->send();
return;

In AJAX mode, this normally will not work as expected unless there are some client-side JavaScript code handling the redirection. To help achieve this goal, this method will send out a "X-Redirect" header instead of "Location".

If you use the "yii" JavaScript module, it will handle the AJAX redirection as described above. Otherwise, you should write the following JavaScript code to handle the redirection:

$document.ajaxComplete(function (event, xhr, settings) {
    var url = xhr && xhr.getResponseHeader('X-Redirect');
    if (url) {
        window.location = url;
    }
});
public $this redirect ( $url, $statusCode 302, $checkAjax true )
$url string|array

The URL to be redirected to. This can be in one of the following formats:

  • a string representing a URL (e.g. "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. yii\helpers\Url::to() will be used to convert the array into a URL.

Any relative URL that starts with a single forward slash "/" will be converted into an absolute one by prepending it with the host info of the current request.

$statusCode integer

The HTTP status code. Defaults to 302. See https://tools.ietf.org/html/rfc2616#section-10 for details about HTTP status code

$checkAjax boolean

Whether to specially handle AJAX (and PJAX) requests. Defaults to true, meaning if the current request is an AJAX or PJAX request, then calling this method will cause the browser to redirect to the given URL. If this is false, a Location header will be sent, which when received as an AJAX/PJAX response, may NOT cause browser redirection. Takes effect only when request header X-Ie-Redirect-Compatibility is absent.

return $this

The response object itself

                public function redirect($url, $statusCode = 302, $checkAjax = true)
{
    if (is_array($url) && isset($url[0])) {
        // ensure the route is absolute
        $url[0] = '/' . ltrim($url[0], '/');
    }
    $request = Yii::$app->getRequest();
    $normalizedUrl = Url::to($url);
    if (
        $normalizedUrl !== null
        && strncmp($normalizedUrl, '/', 1) === 0
        && strncmp($normalizedUrl, '//', 2) !== 0
    ) {
        $normalizedUrl = $request->getHostInfo() . $normalizedUrl;
    }
    if ($checkAjax && $request->getIsAjax()) {
        if (
            in_array($statusCode, [301, 302])
            && preg_match('/Trident\/|MSIE /', (string)$request->userAgent)
        ) {
            $statusCode = 200;
        }
        if ($request->getIsPjax()) {
            $this->getHeaders()->set('X-Pjax-Url', $normalizedUrl);
        } else {
            $this->getHeaders()->set('X-Redirect', $normalizedUrl);
        }
    } else {
        $this->getHeaders()->set('Location', $normalizedUrl);
    }
    $this->setStatusCode($statusCode);
    return $this;
}

            
refresh() public method

Refreshes the current page.

The effect of this method call is the same as the user pressing the refresh button of his browser (without re-posting data).

In a controller action you may use this method like this:

return Yii::$app->getResponse()->refresh();
public yii\web\Response refresh ( $anchor '' )
$anchor string

The anchor that should be appended to the redirection URL. Defaults to empty. Make sure the anchor starts with '#' if you want to specify it.

return yii\web\Response

The response object itself

                public function refresh($anchor = '')
{
    return $this->redirect(Yii::$app->getRequest()->getUrl() . $anchor);
}

            
send() public method

Sends the response to the client.

public void send ( )

                public function send()
{
    if ($this->isSent) {
        return;
    }
    $this->trigger(self::EVENT_BEFORE_SEND);
    $this->prepare();
    $this->trigger(self::EVENT_AFTER_PREPARE);
    $this->sendHeaders();
    $this->sendContent();
    $this->trigger(self::EVENT_AFTER_SEND);
    $this->isSent = true;
}

            
sendContent() protected method

Sends the response content to the client.

protected void sendContent ( )

                protected function sendContent()
{
    if ($this->stream === null) {
        echo $this->content;
        return;
    }
    // Try to reset time limit for big files
    if (!function_exists('set_time_limit') || !@set_time_limit(0)) {
        Yii::warning('set_time_limit() is not available', __METHOD__);
    }
    if (is_callable($this->stream)) {
        $data = call_user_func($this->stream);
        foreach ($data as $datum) {
            echo $datum;
            flush();
        }
        return;
    }
    $chunkSize = 8 * 1024 * 1024; // 8MB per chunk
    if (is_array($this->stream)) {
        list($handle, $begin, $end) = $this->stream;
        // only seek if stream is seekable
        if ($this->isSeekable($handle)) {
            fseek($handle, $begin);
        }
        while (!feof($handle) && ($pos = ftell($handle)) <= $end) {
            if ($pos + $chunkSize > $end) {
                $chunkSize = $end - $pos + 1;
            }
            echo fread($handle, $chunkSize);
            flush(); // Free up memory. Otherwise large files will trigger PHP's memory limit.
        }
        fclose($handle);
    } else {
        while (!feof($this->stream)) {
            echo fread($this->stream, $chunkSize);
            flush();
        }
        fclose($this->stream);
    }
}

            
sendContentAsFile() public method

Sends the specified content as a file to the browser.

Note that this method only prepares the response for file sending. The file is not sent until send() is called explicitly or implicitly. The latter is done after you return from a controller action.

See also sendFile() for an example implementation.

public $this sendContentAsFile ( $content, $attachmentName, $options = [] )
$content string

The content to be sent. The existing $content will be discarded.

$attachmentName string

The file name shown to the user.

$options array

Additional options for sending the file. The following options are supported:

  • mimeType: the MIME type of the content. Defaults to 'application/octet-stream'.
  • inline: boolean, whether the browser should open the file within the browser window. Defaults to false, meaning a download dialog will pop up.
return $this

The response object itself

throws yii\web\RangeNotSatisfiableHttpException

if the requested range is not satisfiable

                public function sendContentAsFile($content, $attachmentName, $options = [])
{
    $headers = $this->getHeaders();
    $contentLength = StringHelper::byteLength($content);
    $range = $this->getHttpRange($contentLength);
    if ($range === false) {
        $headers->set('Content-Range', "bytes */$contentLength");
        throw new RangeNotSatisfiableHttpException();
    }
    list($begin, $end) = $range;
    if ($begin != 0 || $end != $contentLength - 1) {
        $this->setStatusCode(206);
        $headers->set('Content-Range', "bytes $begin-$end/$contentLength");
        $this->content = StringHelper::byteSubstr($content, $begin, $end - $begin + 1);
    } else {
        $this->setStatusCode(200);
        $this->content = $content;
    }
    $mimeType = isset($options['mimeType']) ? $options['mimeType'] : 'application/octet-stream';
    $this->setDownloadHeaders($attachmentName, $mimeType, !empty($options['inline']), $end - $begin + 1);
    $this->format = self::FORMAT_RAW;
    return $this;
}

            
sendCookies() protected method

Sends the cookies to the client.

protected void sendCookies ( )

                protected function sendCookies()
{
    if ($this->_cookies === null) {
        return;
    }
    $request = Yii::$app->getRequest();
    if ($request->enableCookieValidation) {
        if ($request->cookieValidationKey == '') {
            throw new InvalidConfigException(get_class($request) . '::cookieValidationKey must be configured with a secret key.');
        }
        $validationKey = $request->cookieValidationKey;
    }
    foreach ($this->getCookies() as $cookie) {
        $value = $cookie->value;
        if ($cookie->expire != 1 && isset($validationKey)) {
            $value = Yii::$app->getSecurity()->hashData(serialize([$cookie->name, $value]), $validationKey);
        }
        if (PHP_VERSION_ID >= 70300) {
            setcookie($cookie->name, $value, [
                'expires' => $cookie->expire,
                'path' => $cookie->path,
                'domain' => $cookie->domain,
                'secure' => $cookie->secure,
                'httpOnly' => $cookie->httpOnly,
                'sameSite' => !empty($cookie->sameSite) ? $cookie->sameSite : null,
            ]);
        } else {
            // Work around for setting sameSite cookie prior PHP 7.3
            // https://stackoverflow.com/questions/39750906/php-setcookie-samesite-strict/46971326#46971326
            $cookiePath = $cookie->path;
            if (!is_null($cookie->sameSite)) {
                $cookiePath .= '; samesite=' . $cookie->sameSite;
            }
            setcookie($cookie->name, $value, $cookie->expire, $cookiePath, $cookie->domain, $cookie->secure, $cookie->httpOnly);
        }
    }
}

            
sendFile() public method

Sends a file to the browser.

Note that this method only prepares the response for file sending. The file is not sent until send() is called explicitly or implicitly. The latter is done after you return from a controller action.

The following is an example implementation of a controller action that allows requesting files from a directory that is not accessible from web:

public function actionFile($filename)
{
    $storagePath = Yii::getAlias('@app/files');

    // check filename for allowed chars (do not allow ../ to avoid security issue: downloading arbitrary files)
    if (!preg_match('/^[a-z0-9]+\.[a-z0-9]+$/i', $filename) || !is_file("$storagePath/$filename")) {
        throw new \yii\web\NotFoundHttpException('The file does not exists.');
    }
    return Yii::$app->response->sendFile("$storagePath/$filename", $filename);
}

See also:

public $this sendFile ( $filePath, $attachmentName null, $options = [] )
$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.
return $this

The response object itself

                public function sendFile($filePath, $attachmentName = null, $options = [])
{
    if (!isset($options['mimeType'])) {
        $options['mimeType'] = FileHelper::getMimeTypeByExtension($filePath);
    }
    if ($attachmentName === null) {
        $attachmentName = basename($filePath);
    }
    $handle = fopen($filePath, 'rb');
    $this->sendStreamAsFile($handle, $attachmentName, $options);
    return $this;
}

            
sendHeaders() protected method

Sends the response headers to the client.

protected void sendHeaders ( )

                protected function sendHeaders()
{
    if (headers_sent($file, $line)) {
        throw new HeadersAlreadySentException($file, $line);
    }
    if ($this->_headers) {
        foreach ($this->getHeaders() as $name => $values) {
            $name = str_replace(' ', '-', ucwords(str_replace('-', ' ', $name)));
            // set replace for first occurrence of header but false afterwards to allow multiple
            $replace = true;
            foreach ($values as $value) {
                header("$name: $value", $replace);
                $replace = false;
            }
        }
    }
    $statusCode = $this->getStatusCode();
    header("HTTP/{$this->version} {$statusCode} {$this->statusText}");
    $this->sendCookies();
}

            
sendStreamAsFile() public method

Sends the specified stream as a file to the browser.

Note that this method only prepares the response for file sending. The file is not sent until send() is called explicitly or implicitly. The latter is done after you return from a controller action.

See also sendFile() for an example implementation.

public $this sendStreamAsFile ( $handle, $attachmentName, $options = [] )
$handle resource

The handle of the stream to be sent.

$attachmentName string

The file name shown to the user.

$options array

Additional options for sending the file. The following options are supported:

  • mimeType: the MIME type of the content. Defaults to 'application/octet-stream'.
  • inline: boolean, whether the browser should open the file within the browser window. Defaults to false, meaning a download dialog will pop up.
  • fileSize: the size of the content to stream this is useful when size of the content is known and the content is not seekable. Defaults to content size using ftell(). This option is available since version 2.0.4.
return $this

The response object itself

throws yii\web\RangeNotSatisfiableHttpException

if the requested range is not satisfiable

                public function sendStreamAsFile($handle, $attachmentName, $options = [])
{
    $headers = $this->getHeaders();
    if (isset($options['fileSize'])) {
        $fileSize = $options['fileSize'];
    } else {
        if ($this->isSeekable($handle)) {
            fseek($handle, 0, SEEK_END);
            $fileSize = ftell($handle);
        } else {
            $fileSize = 0;
        }
    }
    $range = $this->getHttpRange($fileSize);
    if ($range === false) {
        $headers->set('Content-Range', "bytes */$fileSize");
        throw new RangeNotSatisfiableHttpException();
    }
    list($begin, $end) = $range;
    if ($begin != 0 || $end != $fileSize - 1) {
        $this->setStatusCode(206);
        $headers->set('Content-Range', "bytes $begin-$end/$fileSize");
    } else {
        $this->setStatusCode(200);
    }
    $mimeType = isset($options['mimeType']) ? $options['mimeType'] : 'application/octet-stream';
    $this->setDownloadHeaders($attachmentName, $mimeType, !empty($options['inline']), $end - $begin + 1);
    $this->format = self::FORMAT_RAW;
    $this->stream = [$handle, $begin, $end];
    return $this;
}

            
setDownloadHeaders() public method

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

public $this setDownloadHeaders ( $attachmentName, $mimeType null, $inline false, $contentLength null )
$attachmentName string

The attachment file name

$mimeType string|null

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

The byte length of the file being downloaded. If null, Content-Length header will NOT be set.

return $this

The response object itself

                public function setDownloadHeaders($attachmentName, $mimeType = null, $inline = false, $contentLength = null)
{
    $headers = $this->getHeaders();
    $disposition = $inline ? 'inline' : 'attachment';
    $headers->setDefault('Pragma', 'public')
        ->setDefault('Accept-Ranges', 'bytes')
        ->setDefault('Expires', '0')
        ->setDefault('Cache-Control', 'must-revalidate, post-check=0, pre-check=0')
        ->setDefault('Content-Disposition', $this->getDispositionHeaderValue($disposition, $attachmentName));
    if ($mimeType !== null) {
        $headers->setDefault('Content-Type', $mimeType);
    }
    if ($contentLength !== null) {
        $headers->setDefault('Content-Length', $contentLength);
    }
    return $this;
}

            
setStatusCode() public method

Sets the response status code.

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

public $this setStatusCode ( $value, $text null )
$value integer

The status code

$text string|null

The status text. If not set, it will be set automatically based on the status code.

return $this

The response object itself

throws yii\base\InvalidArgumentException

if the status code is invalid.

                public function setStatusCode($value, $text = null)
{
    if ($value === null) {
        $value = 200;
    }
    $this->_statusCode = (int) $value;
    if ($this->getIsInvalid()) {
        throw new InvalidArgumentException("The HTTP status code is invalid: $value");
    }
    if ($text === null) {
        $this->statusText = isset(static::$httpStatuses[$this->_statusCode]) ? static::$httpStatuses[$this->_statusCode] : '';
    } else {
        $this->statusText = $text;
    }
    return $this;
}

            
setStatusCodeByException() public method (available since version 2.0.12)

Sets the response status code based on the exception.

public $this setStatusCodeByException ( $e )
$e Throwable

The exception object.

return $this

The response object itself

throws yii\base\InvalidArgumentException

if the status code is invalid.

                public function setStatusCodeByException($e)
{
    if ($e instanceof HttpException) {
        $this->setStatusCode($e->statusCode);
    } else {
        $this->setStatusCode(500);
    }
    return $this;
}

            
trigger() public method

Defined in: yii\base\Component::trigger()

Triggers an event.

This method represents the happening of an event. It invokes all attached handlers for the event including class-level handlers.

public void trigger ( $name, yii\base\Event $event null )
$name string

The event name

$event yii\base\Event|null

The event instance. If not set, a default yii\base\Event object will be created.

                public function trigger($name, Event $event = null)
{
    $this->ensureBehaviors();
    $eventHandlers = [];
    foreach ($this->_eventWildcards as $wildcard => $handlers) {
        if (StringHelper::matchWildcard($wildcard, $name)) {
            $eventHandlers[] = $handlers;
        }
    }
    if (!empty($this->_events[$name])) {
        $eventHandlers[] = $this->_events[$name];
    }
    if (!empty($eventHandlers)) {
        $eventHandlers = call_user_func_array('array_merge', $eventHandlers);
        if ($event === null) {
            $event = new Event();
        }
        if ($event->sender === null) {
            $event->sender = $this;
        }
        $event->handled = false;
        $event->name = $name;
        foreach ($eventHandlers as $handler) {
            $event->data = $handler[1];
            call_user_func($handler[0], $event);
            // stop further handling if the event is handled
            if ($event->handled) {
                return;
            }
        }
    }
    // invoke class-level attached handlers
    Event::trigger($this, $name, $event);
}

            
xSendFile() public method

Sends existing file to a browser as a download using x-sendfile.

X-Sendfile is a feature allowing a web application to redirect the request for a file to the webserver that in turn processes the request, this way eliminating the need to perform tasks like reading the file and sending it to the user. When dealing with a lot of files (or very big files) this can lead to a great increase in performance as the web application is allowed to terminate earlier while the webserver is handling the request.

The request is sent to the server through a special non-standard HTTP-header. When the web server encounters the presence of such header it will discard all output and send the file specified by that header using web server internals including all optimizations like caching-headers.

As this header directive is non-standard different directives exists for different web servers applications:

So for this method to work the X-SENDFILE option/module should be enabled by the web server and a proper xHeader should be sent.

Note

This option allows to download files that are not under web folders, and even files that are otherwise protected (deny from all) like .htaccess.

Side effects

If this option is disabled by the web server, when this method is called a download configuration dialog will open but the downloaded file will have 0 bytes.

Known issues

There is a Bug with Internet Explorer 6, 7 and 8 when X-SENDFILE is used over an SSL connection, it will show an error message like this: "Internet Explorer was not able to open this Internet site. The requested site is either unavailable or cannot be found.". You can work around this problem by removing the Pragma-header.

Example

Yii::$app->response->xSendFile('/home/user/Pictures/picture1.jpg');

See also sendFile().

public $this xSendFile ( $filePath, $attachmentName null, $options = [] )
$filePath string

File name with full path

$attachmentName string|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".
return $this

The response object itself

                public function xSendFile($filePath, $attachmentName = null, $options = [])
{
    if ($attachmentName === null) {
        $attachmentName = basename($filePath);
    }
    if (isset($options['mimeType'])) {
        $mimeType = $options['mimeType'];
    } elseif (($mimeType = FileHelper::getMimeTypeByExtension($filePath)) === null) {
        $mimeType = 'application/octet-stream';
    }
    if (isset($options['xHeader'])) {
        $xHeader = $options['xHeader'];
    } else {
        $xHeader = 'X-Sendfile';
    }
    $disposition = empty($options['inline']) ? 'attachment' : 'inline';
    $this->getHeaders()
        ->setDefault($xHeader, $filePath)
        ->setDefault('Content-Type', $mimeType)
        ->setDefault('Content-Disposition', $this->getDispositionHeaderValue($disposition, $attachmentName));
    $this->format = self::FORMAT_RAW;
    return $this;
}

            

Event Details

Hide inherited properties

EVENT_AFTER_PREPARE event of type yii\base\Event

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

EVENT_AFTER_SEND event of type yii\base\Event

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

EVENT_BEFORE_SEND event of type yii\base\Event

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