HumHub Documentation (unofficial)

Response extends Response
in package

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

Tags
author

Qiang Xue qiang.xue@gmail.com

author

Carsten Brandt mail@cebe.cc

since
2.0

Table of Contents

Constants

EVENT_AFTER_PREPARE  = 'afterPrepare'
EVENT_AFTER_SEND  = 'afterSend'
EVENT_BEFORE_SEND  = 'beforeSend'
FORMAT_HTML  = 'html'
FORMAT_JSON  = 'json'
FORMAT_JSONP  = 'jsonp'
FORMAT_RAW  = 'raw'
FORMAT_XML  = 'xml'

Properties

$acceptMimeType  : string
$acceptParams  : array<string|int, mixed>
$behaviors  : array<string|int, Behavior>
$charset  : string|null
$content  : string|null
$cookies  : CookieCollection
$data  : mixed
$downloadHeaders  : string
$exitStatus  : int
$format  : string
$formatters  : array<string|int, mixed>
$headers  : HeaderCollection
$httpStatuses  : array<string|int, mixed>
$isClientError  : bool
$isEmpty  : bool
$isForbidden  : bool
$isInformational  : bool
$isInvalid  : bool
$isNotFound  : bool
$isOk  : bool
$isRedirection  : bool
$isSent  : bool
$isServerError  : bool
$isSuccessful  : bool
$statusCode  : int
$statusCodeByException  : Throwable
$statusText  : string
$stream  : resource|array<string|int, mixed>|callable
$version  : string|null
$_behaviors  : array<string|int, Behavior>|null
$_cookies  : mixed
$_events  : array<string|int, mixed>
$_eventWildcards  : array<string|int, mixed>
$_headers  : HeaderCollection
$_statusCode  : int

Methods

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

Constants

EVENT_AFTER_PREPARE

public mixed EVENT_AFTER_PREPARE = 'afterPrepare'
Tags
event

\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

public mixed EVENT_AFTER_SEND = 'afterSend'
Tags
event

\yii\base\Event an event that is triggered at the end of [[send()]].

EVENT_BEFORE_SEND

public mixed EVENT_BEFORE_SEND = 'beforeSend'
Tags
event

\yii\base\Event an event that is triggered at the beginning of [[send()]].

FORMAT_HTML

public mixed FORMAT_HTML = 'html'

FORMAT_JSON

public mixed FORMAT_JSON = 'json'

FORMAT_JSONP

public mixed FORMAT_JSONP = 'jsonp'

FORMAT_RAW

public mixed FORMAT_RAW = 'raw'

FORMAT_XML

public mixed FORMAT_XML = 'xml'

Properties

$acceptMimeType

public string $acceptMimeType

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

$acceptParams

public array<string|int, mixed> $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 [[\yii\filters\ContentNegotiator]].

$behaviors read-only

public array<string|int, Behavior> $behaviors

List of behaviors attached to this component.

$charset

public string|null $charset

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

$content

public string|null $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.

Tags
see
data

$data

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

Tags
see
content

$downloadHeaders write-only

public string $downloadHeaders

The attachment file name.

$exitStatus

public int $exitStatus = 0

the exit status. Exit statuses should be in the range 0 to 254. The status 0 means the program terminates successfully.

$format

public string $format = self::FORMAT_HTML

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

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

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

Tags
see
formatters

$formatters

public array<string|int, mixed> $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.

Tags
see
format
see
defaultFormatters

$httpStatuses

public static array<string|int, mixed> $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']

list of HTTP status codes and the corresponding texts

$isClientError read-only

public bool $isClientError

Whether this response indicates a client error.

$isEmpty read-only

public bool $isEmpty

Whether this response is empty.

$isForbidden read-only

public bool $isForbidden

Whether this response indicates the current request is forbidden.

$isInformational read-only

public bool $isInformational

Whether this response is informational.

$isInvalid read-only

public bool $isInvalid

Whether this response has a valid [[statusCode]].

$isNotFound read-only

public bool $isNotFound

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

$isOk read-only

public bool $isOk

Whether this response is OK.

$isRedirection read-only

public bool $isRedirection

Whether this response is a redirection.

$isSent

public bool $isSent = false

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

$isServerError read-only

public bool $isServerError

Whether this response indicates a server error.

$isSuccessful read-only

public bool $isSuccessful

Whether this response is successful.

$statusCode

public int $statusCode

The HTTP status code to send with the response.

$statusCodeByException write-only

public Throwable $statusCodeByException

The exception object.

$statusText

public string $statusText = 'OK'

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

Tags
see
httpStatuses

$stream

public resource|array<string|int, mixed>|callable $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. 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 string|null $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.

$_behaviors

private array<string|int, Behavior>|null $_behaviors

the attached behaviors (behavior name => behavior). This is null when not initialized.

$_events

private array<string|int, mixed> $_events = []

the attached event handlers (event name => handlers)

$_eventWildcards

private array<string|int, mixed> $_eventWildcards = []

the event handlers attached for wildcard patterns (event name wildcard => handlers)

Tags
since
2.0.14

$_statusCode

private int $_statusCode = 200

the HTTP status code to send with the response.

Methods

__call()

Calls the named method which is not a class method.

public __call(string $name, array<string|int, mixed> $params) : mixed

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.

Parameters
$name : string

the method name

$params : array<string|int, mixed>

method parameters

Tags
throws
UnknownMethodException

when calling unknown method

Return values
mixed

the method return value

__clone()

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

public __clone() : mixed

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

__construct()

Constructor.

public __construct([array<string|int, mixed> $config = [] ]) : mixed

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.
Parameters
$config : array<string|int, mixed> = []

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

__get()

Returns the value of a component property.

public __get(string $name) : mixed

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

Parameters
$name : string

the property name

Tags
throws
UnknownPropertyException

if the property is not defined

throws
InvalidCallException

if the property is write-only.

see
__set()
Return values
mixed

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

__isset()

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

public __isset(string $name) : bool

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

Parameters
$name : string

the property name or the event name

Tags
see
https://www.php.net/manual/en/function.isset.php
Return values
bool

whether the named property is set

__set()

Sets the value of a component property.

public __set(string $name, mixed $value) : mixed

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

Parameters
$name : string

the property name or the event name

$value : mixed

the property value

Tags
throws
UnknownPropertyException

if the property is not defined

throws
InvalidCallException

if the property is read-only.

see
__get()

__unset()

Sets a component property to be null.

public __unset(string $name) : mixed

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

Parameters
$name : string

the property name

Tags
throws
InvalidCallException

if the property is read only.

see
https://www.php.net/manual/en/function.unset.php

attachBehavior()

Attaches a behavior to this component.

public attachBehavior(string $name, string|array<string|int, mixed>|Behavior $behavior) : Behavior

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 [[Behavior::attach()]] method.

Parameters
$name : string

the name of the behavior.

$behavior : string|array<string|int, mixed>|Behavior

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

  • a [[Behavior]] object
  • a string specifying the behavior class
  • an object configuration array that will be passed to [[Yii::createObject()]] to create the behavior object.
Tags
see
detachBehavior()
Return values
Behavior

the behavior object

attachBehaviors()

Attaches a list of behaviors to the component.

public attachBehaviors(array<string|int, mixed> $behaviors) : mixed

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

Parameters
$behaviors : array<string|int, mixed>

list of behaviors to be attached to the component

Tags
see
attachBehavior()

behaviors()

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

public behaviors() : array<string|int, mixed>

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

Return values
array<string|int, mixed>

the behavior configurations.

canGetProperty()

Returns a value indicating whether a property can be read.

public canGetProperty(string $name[, bool $checkVars = true ][, bool $checkBehaviors = true ]) : bool

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).
Parameters
$name : string

the property name

$checkVars : bool = true

whether to treat member variables as properties

$checkBehaviors : bool = true

whether to treat behaviors' properties as properties of this component

Tags
see
canSetProperty()
Return values
bool

whether the property can be read

canSetProperty()

Returns a value indicating whether a property can be set.

public canSetProperty(string $name[, bool $checkVars = true ][, bool $checkBehaviors = true ]) : bool

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).
Parameters
$name : string

the property name

$checkVars : bool = true

whether to treat member variables as properties

$checkBehaviors : bool = true

whether to treat behaviors' properties as properties of this component

Tags
see
canGetProperty()
Return values
bool

whether the property can be written

className()

Returns the fully qualified name of this class.

public static className() : string
Tags
deprecated

since 2.0.14. On PHP >=5.5, use ::class instead.

Return values
string

the fully qualified name of this class.

clear()

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

public clear() : mixed

clearOutputBuffers()

Removes all existing output buffers.

public clearOutputBuffers() : mixed

detachBehavior()

Detaches a behavior from the component.

public detachBehavior(string $name) : Behavior|null

The behavior's [[Behavior::detach()]] method will be invoked.

Parameters
$name : string

the behavior's name.

Return values
Behavior|null

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

detachBehaviors()

Detaches all behaviors from the component.

public detachBehaviors() : mixed

ensureBehaviors()

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

public ensureBehaviors() : mixed

getBehavior()

Returns the named behavior object.

public getBehavior(string $name) : Behavior|null
Parameters
$name : string

the behavior name

Return values
Behavior|null

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

getBehaviors()

Returns all behaviors attached to this component.

public getBehaviors() : array<string|int, Behavior>
Return values
array<string|int, Behavior>

list of behaviors attached to this component

getCookies()

Returns the cookie collection.

public getCookies() : CookieCollection

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']);
Return values
CookieCollection

the cookie collection.

getHeaders()

Returns the header collection.

public getHeaders() : HeaderCollection

The header collection contains the currently registered HTTP headers.

Return values
HeaderCollection

the header collection

getIsClientError()

public getIsClientError() : bool
Return values
bool

whether this response indicates a client error

getIsEmpty()

public getIsEmpty() : bool
Return values
bool

whether this response is empty

getIsForbidden()

public getIsForbidden() : bool
Return values
bool

whether this response indicates the current request is forbidden

getIsInformational()

public getIsInformational() : bool
Return values
bool

whether this response is informational

getIsInvalid()

public getIsInvalid() : bool
Return values
bool

whether this response has a valid [[statusCode]].

getIsNotFound()

public getIsNotFound() : bool
Return values
bool

whether this response indicates the currently requested resource is not found

getIsOk()

public getIsOk() : bool
Return values
bool

whether this response is OK

getIsRedirection()

public getIsRedirection() : bool
Return values
bool

whether this response is a redirection

getIsServerError()

public getIsServerError() : bool
Return values
bool

whether this response indicates a server error

getIsSuccessful()

public getIsSuccessful() : bool
Return values
bool

whether this response is successful

getStatusCode()

public getStatusCode() : int
Return values
int

the HTTP status code to send with the response.

hasEventHandlers()

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

public hasEventHandlers(string $name) : bool
Parameters
$name : string

the event name

Return values
bool

whether there is any handler attached to the event.

hasMethod()

Returns a value indicating whether a method is defined.

public hasMethod(string $name[, bool $checkBehaviors = true ]) : bool

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).
Parameters
$name : string

the property name

$checkBehaviors : bool = true

whether to treat behaviors' methods as methods of this component

Return values
bool

whether the method is defined

hasProperty()

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

public hasProperty(string $name[, bool $checkVars = true ][, bool $checkBehaviors = true ]) : bool

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).
Parameters
$name : string

the property name

$checkVars : bool = true

whether to treat member variables as properties

$checkBehaviors : bool = true

whether to treat behaviors' properties as properties of this component

Tags
see
canGetProperty()
see
canSetProperty()
Return values
bool

whether the property is defined

init()

Initializes this component.

public init() : mixed

off()

Detaches an existing event handler from this component.

public off(string $name[, callable|null $handler = null ]) : bool

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.

Parameters
$name : string

event name

$handler : callable|null = null

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

Tags
see
on()
Return values
bool

if a handler is found and detached

on()

Attaches an event handler to an event.

public on(string $name, callable $handler[, mixed $data = null ][, bool $append = true ]) : mixed

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 [[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.');
});
Parameters
$name : string

the event name

$handler : callable

the event handler

$data : mixed = null

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 [[Event::data]].

$append : bool = true

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.

Tags
see
off()

redirect()

Redirects the browser to the specified URL.

public redirect(string|array<string|int, mixed> $url[, int $statusCode = 302 ][, bool $checkAjax = true ]) : $this

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

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

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

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

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

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

$document.ajaxComplete(function (event, xhr, settings) {
    var url = xhr && xhr.getResponseHeader('X-Redirect');
    if (url) {
        window.location = url;
    }
});
Parameters
$url : string|array<string|int, mixed>

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

  • a string representing a URL (e.g. "https://example.com")
  • a string representing a URL alias (e.g. "@example.com")
  • an array in the format of [$route, ...name-value pairs...] (e.g. ['site/index', 'ref' => 1]). Note that the route is with respect to the whole application, instead of relative to a controller or module. [[Url::to()]] will be used to convert the array into a URL.

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

$statusCode : int = 302

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

$checkAjax : bool = true

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 values
$this

the response object itself

refresh()

Refreshes the current page.

public refresh([string $anchor = '' ]) : Response

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

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

return Yii::$app->getResponse()->refresh();
Parameters
$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 values
Response

the response object itself

send()

Sends the response to the client.

public send() : mixed

sendContentAsFile()

Sends the specified content as a file to the browser.

public sendContentAsFile(string $content, string $attachmentName[, array<string|int, mixed> $options = [] ]) : $this

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

Parameters
$content : string

the content to be sent. The existing [[content]] will be discarded.

$attachmentName : string

the file name shown to the user.

$options : array<string|int, mixed> = []

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.
Tags
throws
RangeNotSatisfiableHttpException

if the requested range is not satisfiable

see
sendFile()

for an example implementation.

Return values
$this

the response object itself

sendFile()

Sends a file to the browser.

public sendFile(string $filePath[, string|null $attachmentName = null ][, array<string|int, mixed> $options = [] ]) : $this

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

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

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

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

the path of the file to be sent.

$attachmentName : string|null = null

the file name shown to the user. If null, it will be determined from $filePath.

$options : array<string|int, mixed> = []

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.
Tags
see
sendContentAsFile()
see
sendStreamAsFile()
see
xSendFile()
Return values
$this

the response object itself

sendStreamAsFile()

Sends the specified stream as a file to the browser.

public sendStreamAsFile(resource $handle, string $attachmentName[, array<string|int, mixed> $options = [] ]) : $this

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

Parameters
$handle : resource

the handle of the stream to be sent.

$attachmentName : string

the file name shown to the user.

$options : array<string|int, mixed> = []

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.
Tags
throws
RangeNotSatisfiableHttpException

if the requested range is not satisfiable

see
sendFile()

for an example implementation.

Return values
$this

the response object itself

setDownloadHeaders()

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

public setDownloadHeaders(string $attachmentName[, string|null $mimeType = null ][, bool $inline = false ][, int|null $contentLength = null ]) : $this
Parameters
$attachmentName : string

the attachment file name

$mimeType : string|null = null

the MIME type for the response. If null, Content-Type header will NOT be set.

$inline : bool = false

whether the browser should open the file within the browser window. Defaults to false, meaning a download dialog will pop up.

$contentLength : int|null = null

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

Return values
$this

the response object itself

setStatusCode()

Sets the response status code.

public setStatusCode(int $value[, string|null $text = null ]) : $this

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

Parameters
$value : int

the status code

$text : string|null = null

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

Tags
throws
InvalidArgumentException

if the status code is invalid.

Return values
$this

the response object itself

setStatusCodeByException()

Sets the response status code based on the exception.

public setStatusCodeByException(Throwable $e) : $this
Parameters
$e : Throwable

the exception object.

Tags
throws
InvalidArgumentException

if the status code is invalid.

since
2.0.12
Return values
$this

the response object itself

trigger()

Triggers an event.

public trigger(string $name[, Event|null $event = null ]) : mixed

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

Parameters
$name : string

the event name

$event : Event|null = null

the event instance. If not set, a default [[Event]] object will be created.

xSendFile()

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

public xSendFile(string $filePath[, string|null $attachmentName = null ][, array<string|int, mixed> $options = [] ]) : $this

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

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

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

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

Note

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

Side effects

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

Known issues

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

Example

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

file name with full path

$attachmentName : string|null = null

file name shown to the user. If null, it will be determined from $filePath.

$options : array<string|int, mixed> = []

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".
Tags
see
sendFile()
Return values
$this

the response object itself

defaultFormatters()

protected defaultFormatters() : array<string|int, mixed>
Return values
array<string|int, mixed>

the formatters that are supported by default

getDispositionHeaderValue()

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

protected getDispositionHeaderValue(string $disposition, string $attachmentName) : string

Fallback name:

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

UTF name:

  • Causes issues if contains path separator characters such as \ or /.
  • Should be urlencoded since headers are ASCII-only.
  • Could be omitted if it exactly matches fallback name.
Parameters
$disposition : string
$attachmentName : string
Tags
since
2.0.10
Return values
string

getHttpRange()

Determines the HTTP range given in the request.

protected getHttpRange(int $fileSize) : array<string|int, mixed>|bool
Parameters
$fileSize : int

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

Return values
array<string|int, mixed>|bool

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

sendContent()

Sends the response content to the client.

protected sendContent() : mixed

sendCookies()

Sends the cookies to the client.

protected sendCookies() : mixed

sendHeaders()

Sends the response headers to the client.

protected sendHeaders() : mixed

attachBehaviorInternal()

Attaches a behavior to this component.

private attachBehaviorInternal(string|int $name, string|array<string|int, mixed>|Behavior $behavior) : Behavior
Parameters
$name : string|int

the name of the behavior. If this is an integer, it means the behavior is an anonymous one. Otherwise, the behavior is a named one and any existing behavior with the same name will be detached first.

$behavior : string|array<string|int, mixed>|Behavior

the behavior to be attached

Return values
Behavior

the attached behavior.

isSeekable()

Checks if a stream is seekable

private isSeekable(mixed $handle) : bool
Parameters
$handle : mixed
Return values
bool

        
On this page

Search results