1 追蹤者

類別 yii\web\Response

繼承關係yii\web\Response » yii\base\Response » yii\base\Component » yii\base\BaseObject
實作yii\base\Configurable
自版本起可用2.0
原始碼 https://github.com/yiisoft/yii2/blob/master/framework/web/Response.php

web Response 類別代表一個 HTTP 回應。

它持有要傳送至客戶端的 $headers$cookies$content。它也控制 HTTP 狀態碼

Response 預設在 yii\web\Application 中配置為應用程式元件。您可以透過 Yii::$app->response 存取該實例。

您可以透過在應用程式設定檔的 components 下新增一個陣列來修改其配置,如下列範例所示

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

有關 Response 的更多詳細資訊和使用方法,請參閱關於回應的指南文章

公共屬性

隱藏繼承的屬性

屬性 類型 描述 定義於
$acceptMimeType string 從請求 ACCEPT header 中選擇用於此回應的 MIME 類型 (例如 application/json)。 yii\web\Response
$acceptParams array 選擇的 MIME 類型相關聯的參數 (例如 ['q' => 1, 'version' => '1.0'])。 yii\web\Response
$behaviors yii\base\Behavior[] 附加到此元件的行為列表。 yii\base\Component
$charset string|null 文字回應的字元集。 yii\web\Response
$content string|null 回應內容。 yii\web\Response
$cookies yii\web\CookieCollection Cookie 集合。 yii\web\Response
$data mixed 原始回應資料。 yii\web\Response
$downloadHeaders string 附件檔案名稱。 yii\web\Response
$exitStatus integer 退出狀態。 yii\base\Response
$format string 回應格式。 yii\web\Response
$formatters array 將資料轉換為指定 $format 回應內容的格式器。 yii\web\Response
$headers yii\web\HeaderCollection 標頭集合。 yii\web\Response
$httpStatuses array HTTP 狀態碼及其對應文字的列表 yii\web\Response
$isClientError 布林值 此回應是否表示用戶端錯誤。 yii\web\Response
$isEmpty 布林值 此回應是否為空。 yii\web\Response
$isForbidden 布林值 此回應是否表示目前請求被禁止。 yii\web\Response
$isInformational 布林值 此回應是否為資訊性回應。 yii\web\Response
$isInvalid 布林值 此回應是否具有有效的 $statusCode yii\web\Response
$isNotFound 布林值 此回應是否表示目前請求的資源未找到。 yii\web\Response
$isOk 布林值 此回應是否為 OK。 yii\web\Response
$isRedirection 布林值 此回應是否為重新導向。 yii\web\Response
$isSent 布林值 回應是否已發送。 yii\web\Response
$isServerError 布林值 此回應是否表示伺服器錯誤。 yii\web\Response
$isSuccessful 布林值 此回應是否成功。 yii\web\Response
$statusCode integer 隨回應發送的 HTTP 狀態碼。 yii\web\Response
$statusCodeByException Throwable 例外物件。 yii\web\Response
$statusText string 與狀態碼一起出現的 HTTP 狀態描述。 yii\web\Response
$stream resource|array|callable 要發送的串流。 yii\web\Response
$version string|null 要使用的 HTTP 協定版本。 yii\web\Response

公開方法

隱藏繼承方法

方法 描述 定義於
__call() 呼叫未定義為類別方法的具名方法。 yii\base\Component
__clone() 在透過複製現有物件建立新物件後,會呼叫此方法。 yii\base\Component
__construct() 建構子。 yii\base\BaseObject
__get() 傳回元件屬性的值。 yii\base\Component
__isset() 檢查屬性是否已設定,即已定義且非空值。 yii\base\Component
__set() 設定元件屬性的值。 yii\base\Component
__unset() 將元件屬性設定為 null。 yii\base\Component
attachBehavior() 將行為附加到此元件。 yii\base\Component
attachBehaviors() 將行為列表附加到元件。 yii\base\Component
behaviors() 傳回此元件應表現為的行為列表。 yii\base\Component
canGetProperty() 傳回一個值,指示屬性是否可讀取。 yii\base\Component
canSetProperty() 傳回一個值,指示屬性是否可設定。 yii\base\Component
className() 傳回此類別的完整限定名稱。 yii\base\BaseObject
clear() 清除回應的標頭、Cookie、內容、狀態碼。 yii\web\Response
clearOutputBuffers() 移除所有現有的輸出緩衝區。 yii\base\Response
detachBehavior() 從元件分離行為。 yii\base\Component
detachBehaviors() 從元件分離所有行為。 yii\base\Component
ensureBehaviors() 確保在 behaviors() 中宣告的行為已附加到此元件。 yii\base\Component
getBehavior() 傳回具名行為物件。 yii\base\Component
getBehaviors() 傳回附加到此元件的所有行為。 yii\base\Component
getCookies() 傳回 Cookie 集合。 yii\web\Response
getHeaders() 傳回標頭集合。 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() 傳回一個值,指示是否有名稱事件附加任何處理常式。 yii\base\Component
hasMethod() 傳回一個值,指示是否已定義方法。 yii\base\Component
hasProperty() 傳回一個值,指示是否為此元件定義屬性。 yii\base\Component
init() 初始化此元件。 yii\web\Response
off() 從此元件分離現有的事件處理常式。 yii\base\Component
on() 將事件處理常式附加到事件。 yii\base\Component
redirect() 將瀏覽器重新導向到指定的 URL。 yii\web\Response
refresh() 重新整理目前頁面。 yii\web\Response
send() 將回應發送到用戶端。 yii\web\Response
sendContentAsFile() 將指定的內容作為檔案傳送到瀏覽器。 yii\web\Response
sendFile() 將檔案傳送到瀏覽器。 yii\web\Response
sendStreamAsFile() 將指定的串流作為檔案傳送到瀏覽器。 yii\web\Response
setDownloadHeaders() 為檔案下載目的設定一組預設的 HTTP 標頭。 yii\web\Response
setStatusCode() 設定回應狀態碼。 yii\web\Response
setStatusCodeByException() 根據例外設定回應狀態碼。 yii\web\Response
trigger() 觸發事件。 yii\base\Component
xSendFile() 使用 x-sendfile 將現有檔案作為下載傳送到瀏覽器。 yii\web\Response

受保護方法

隱藏繼承方法

方法 描述 定義於
defaultFormatters() yii\web\Response
getDispositionHeaderValue() 傳回 Content-Disposition 標頭值,該值可安全地用於新舊瀏覽器。 yii\web\Response
getHttpRange() 決定請求中給定的 HTTP 範圍。 yii\web\Response
prepare() 準備發送回應。 yii\web\Response
sendContent() 將回應內容發送到用戶端。 yii\web\Response
sendCookies() 將 Cookie 發送到用戶端。 yii\web\Response
sendHeaders() 將回應標頭發送到用戶端。 yii\web\Response

事件

隱藏繼承事件

事件 類型 描述 定義於
EVENT_AFTER_PREPARE yii\base\Event send() 中呼叫 prepare() 之後立即觸發的事件。 yii\web\Response
EVENT_AFTER_SEND yii\base\Event send() 結束時觸發的事件。 yii\web\Response
EVENT_BEFORE_SEND yii\base\Event send() 開始時觸發的事件。 yii\web\Response

常數

隱藏繼承常數

常數 描述 定義於
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

屬性詳細資訊

隱藏繼承的屬性

$acceptMimeType 公開屬性

從請求 ACCEPT 標頭中選取用於此回應的 MIME 類型(例如 application/json)。此屬性主要由 yii\filters\ContentNegotiator 設定。

public string $acceptMimeType null
$acceptParams 公開屬性

選取的 MIME 類型 相關聯的參數(例如 ['q' => 1, 'version' => '1.0'])。這是與 ACCEPT HTTP 標頭中的 $acceptMimeType 相關聯的名稱-值組列表。此屬性主要由 yii\filters\ContentNegotiator 設定。

public array $acceptParams = []
$charset 公開屬性

文字回應的字元集。如果未設定,將使用 yii\web\Application::$charset 的值。

public string|null $charset null
$content 公開屬性

回應內容。當 $data 不為 null 時,在回應發送出去時,會根據 $format 將其轉換為 $content

另請參閱 $data

public string|null $content null
$cookies 公開屬性

Cookie 集合。

$data 公開屬性

原始回應資料。當此項不為 null 時,在回應發送出去時,會根據 $format 將其轉換為 $content

另請參閱 $content

public mixed $data null
$downloadHeaders 公開屬性

附件檔案名稱。

public string $downloadHeaders null
$format 公開屬性

回應格式。這決定了當 $content 未設定時,如何將 $data 轉換為 $content。此屬性的值必須是在 $formatters 陣列中宣告的其中一個鍵。預設情況下,支援以下格式:

  • FORMAT_RAW:資料將被視為回應內容,不進行任何轉換。不會新增額外的 HTTP 標頭。
  • FORMAT_HTML:資料將被視為回應內容,不進行任何轉換。"Content-Type" 標頭將設定為 "text/html"。
  • FORMAT_JSON:資料將被轉換為 JSON 格式,並且 "Content-Type" 標頭將設定為 "application/json"。
  • FORMAT_JSONP:資料將被轉換為 JSONP 格式,並且 "Content-Type" 標頭將設定為 "text/javascript"。請注意,在這種情況下,$data 必須是一個包含 "data" 和 "callback" 元素的陣列。前者指的是要發送的實際資料,而後者指的是 JavaScript 回呼的名稱。
  • FORMAT_XML:資料將被轉換為 XML 格式。有關更多詳細資訊,請參閱 yii\web\XmlResponseFormatter

您可以透過設定 $formatters 自訂格式化過程或支援其他格式。

另請參閱 $formatters

public string $format self::FORMAT_HTML
$formatters 公開屬性

將資料轉換為指定 $format 回應內容的格式器。陣列鍵是格式名稱,陣列值是用於建立格式器物件的相應組態。

另請參閱

public array $formatters = []
$headers 公開屬性

標頭集合。

$httpStatuses 公開靜態屬性

HTTP 狀態碼及其對應文字的列表

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 boolean $isClientError null
$isEmpty 公開屬性

此回應是否為空。

public boolean $isEmpty null
$isForbidden 公開屬性

此回應是否表示目前請求被禁止。

public boolean $isForbidden null
$isInformational public 屬性

此回應是否為資訊性回應。

public boolean $isInformational null
$isInvalid public 屬性

此回應是否具有有效的 $statusCode

public boolean $isInvalid null
$isNotFound public 屬性

此回應是否表示目前請求的資源未找到。

public boolean $isNotFound null
$isOk public 屬性

此回應是否為 OK。

public boolean $isOk null
$isRedirection public 屬性

此回應是否為重新導向。

public boolean $isRedirection null
$isSent public 屬性

回應是否已發送。如果為 true,呼叫 send() 將不會有任何作用。

public boolean $isSent false
$isServerError public 屬性

此回應是否表示伺服器錯誤。

public boolean $isServerError null
$isSuccessful public 屬性

此回應是否成功。

public boolean $isSuccessful null
$statusCode public 屬性

隨回應發送的 HTTP 狀態碼。

public integer $statusCode null
$statusCodeByException public 屬性

例外物件。

$statusText public 屬性

與狀態碼一起出現的 HTTP 狀態描述。

另請參閱 $httpStatuses

public string $statusText 'OK'
$stream public 屬性

要發送的串流。這可以是串流控制代碼或串流控制代碼陣列、起始位置和結束位置。或者,它可以設定為可呼叫的物件,該物件會傳回(或 產生 (yields))應逐一 echo 和刷新的字串陣列。

請注意,當設定此屬性時,$data$content 屬性將被 send() 忽略。

$version public 屬性

要使用的 HTTP 協定版本。如果未設定,它將透過 $_SERVER['SERVER_PROTOCOL'] 判斷,如果不可用,則為 '1.1'。

public string|null $version null

方法詳細資訊

隱藏繼承方法

__call() public 方法

定義於: yii\base\Component::__call()

呼叫未定義為類別方法的具名方法。

此方法將檢查是否有任何附加的行為具有指定的名稱方法,並在可用的情況下執行它。

請勿直接呼叫此方法,因為它是 PHP 魔術方法,當呼叫未知方法時,將會隱式呼叫它。

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

方法名稱

$params array

方法參數

return mixed

方法傳回值

throws yii\base\UnknownMethodException

當呼叫未知方法時

                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 方法

定義於: yii\base\Component::__clone()

在透過複製現有物件建立新物件後,會呼叫此方法。

它會移除所有行為,因為它們附加到舊物件。

public void __clone ( )

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

            
__construct() public 方法

定義於: yii\base\BaseObject::__construct()

建構子。

預設實作會執行兩件事

  • 使用給定的組態 $config 初始化物件。
  • 呼叫 init()

如果在子類別中覆寫此方法,建議

  • 建構子的最後一個參數是組態陣列,例如此處的 $config
  • 在建構子的結尾呼叫父類別實作。
public void __construct ( $config = [] )
$config array

將用於初始化物件屬性的名稱-值配對

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

            
__get() public 方法

定義於: yii\base\Component::__get()

傳回元件屬性的值。

此方法將依以下順序檢查並採取相應措施

  • getter 定義的屬性:傳回 getter 結果
  • 行為的屬性:傳回行為屬性值

請勿直接呼叫此方法,因為它是 PHP 魔術方法,當執行 $value = $component->property; 時,將會隱式呼叫它。

另請參閱 __set()

public mixed __get ( $name )
$name string

屬性名稱

return mixed

屬性值或行為屬性的值

throws yii\base\UnknownPropertyException

如果未定義屬性

throws yii\base\InvalidCallException

如果屬性為唯寫。

                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 方法

定義於: yii\base\Component::__isset()

檢查屬性是否已設定,即已定義且非空值。

此方法將依以下順序檢查並採取相應措施

  • setter 定義的屬性:傳回屬性是否已設定
  • 行為的屬性:傳回屬性是否已設定
  • 針對不存在的屬性傳回 false

請勿直接呼叫此方法,因為它是 PHP 魔術方法,當執行 isset($component->property) 時,將會隱式呼叫它。

另請參閱 https://php.dev.org.tw/manual/en/function.isset.php

public boolean __isset ( $name )
$name string

屬性名稱或事件名稱

return 布林值

具名屬性是否已設定

                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 方法

定義於: yii\base\Component::__set()

設定元件屬性的值。

此方法將依以下順序檢查並採取相應措施

  • setter 定義的屬性:設定屬性值
  • 格式為 "on xyz" 的事件:將處理常式附加到事件 "xyz"
  • 格式為 "as xyz" 的行為:附加名為 "xyz" 的行為
  • 行為的屬性:設定行為屬性值

請勿直接呼叫此方法,因為它是 PHP 魔術方法,當執行 $component->property = $value; 時,將會隱式呼叫它。

另請參閱 __get()

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

屬性名稱或事件名稱

$value mixed

屬性值

throws yii\base\UnknownPropertyException

如果未定義屬性

throws yii\base\InvalidCallException

如果屬性為唯讀。

                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 方法

定義於: yii\base\Component::__unset()

將元件屬性設定為 null。

此方法將依以下順序檢查並採取相應措施

  • setter 定義的屬性:將屬性值設定為 null
  • 行為的屬性:將屬性值設定為 null

請勿直接呼叫此方法,因為它是 PHP 魔術方法,當執行 unset($component->property) 時,將會隱式呼叫它。

另請參閱 https://php.dev.org.tw/manual/en/function.unset.php

public void __unset ( $name )
$name string

屬性名稱

throws yii\base\InvalidCallException

如果屬性為唯讀。

                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 方法

定義於: yii\base\Component::attachBehavior()

將行為附加到此元件。

此方法將根據給定的組態建立行為物件。之後,將透過呼叫 yii\base\Behavior::attach() 方法,將行為物件附加到此元件。

另請參閱 detachBehavior()

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

行為的名稱。

$behavior string|array|yii\base\Behavior

行為組態。這可以是下列其中一項

return yii\base\Behavior

行為物件

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

            
attachBehaviors() public 方法

定義於: yii\base\Component::attachBehaviors()

將行為列表附加到元件。

每個行為都依其名稱編製索引,並且應該是 yii\base\Behavior 物件、指定行為類別的字串,或是用於建立行為的組態陣列。

另請參閱 attachBehavior()

public void attachBehaviors ( $behaviors )
$behaviors array

要附加到元件的行為清單

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

            
behaviors() public 方法

定義於: yii\base\Component::behaviors()

傳回此元件應表現為的行為列表。

子類別可以覆寫此方法,以指定它們要表現的行為。

此方法的傳回值應該是以行為名稱編製索引的行為物件或組態陣列。行為組態可以是指定行為類別的字串,或是以下結構的陣列

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

請注意,行為類別必須從 yii\base\Behavior 擴充。行為可以使用名稱或匿名方式附加。當名稱用作陣列索引鍵時,使用此名稱,稍後可以使用 getBehavior() 擷取行為,或使用 detachBehavior() 分離行為。匿名行為無法擷取或分離。

在此方法中宣告的行為將自動(依需求)附加到元件。

public array behaviors ( )
return array

行為組態。

                public function behaviors()
{
    return [];
}

            
canGetProperty() public 方法

定義於: yii\base\Component::canGetProperty()

傳回一個值,指示屬性是否可讀取。

如果符合以下條件,則可以讀取屬性

  • 類別具有與指定名稱關聯的 getter 方法(在這種情況下,屬性名稱不區分大小寫);
  • 類別具有具有指定名稱的成員變數(當 $checkVars 為 true 時);
  • 附加的行為具有給定名稱的可讀屬性(當 $checkBehaviors 為 true 時)。

另請參閱 canSetProperty()

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

屬性名稱

$checkVars 布林值

是否將成員變數視為屬性

$checkBehaviors 布林值

是否將行為的屬性視為此元件的屬性

return 布林值

屬性是否可讀

                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 方法

定義於: yii\base\Component::canSetProperty()

傳回一個值,指示屬性是否可設定。

如果符合以下條件,則可以寫入屬性

  • 類別具有與指定名稱關聯的 setter 方法(在這種情況下,屬性名稱不區分大小寫);
  • 類別具有具有指定名稱的成員變數(當 $checkVars 為 true 時);
  • 附加的行為具有給定名稱的可寫屬性(當 $checkBehaviors 為 true 時)。

另請參閱 canGetProperty()

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

屬性名稱

$checkVars 布林值

是否將成員變數視為屬性

$checkBehaviors 布林值

是否將行為的屬性視為此元件的屬性

return 布林值

屬性是否可寫入

                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 方法
自 2.0.14 版本起已過時。在 PHP >=5.5 上,請改用 ::class

定義於: yii\base\BaseObject::className()

傳回此類別的完整限定名稱。

public static string className ( )
return string

此類別的完整限定名稱。

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

            
clear() public 方法

清除回應的標頭、Cookie、內容、狀態碼。

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

移除所有現有的輸出緩衝區。

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

預設支援的格式器

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

從元件分離行為。

將會調用 behavior 的 yii\base\Behavior::detach() 方法。

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

Behavior 的名稱。

return yii\base\Behavior|null

已分離的 behavior。如果 behavior 不存在則為 Null。

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

從元件分離所有行為。

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

確保在 behaviors() 中宣告的行為已附加到此元件。

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

傳回具名行為物件。

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

Behavior 的名稱

return yii\base\Behavior|null

Behavior 物件,如果 behavior 不存在則為 null

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

            
getBehaviors() public method

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

傳回附加到此元件的所有行為。

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

附加到此元件的 behavior 列表

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

            
getCookies() public method

傳回 Cookie 集合。

透過返回的 cookie 集合,您可以如下新增或移除 cookie,

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

Cookie 集合。

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

            
getDispositionHeaderValue() protected method (available since version 2.0.10)

傳回 Content-Disposition 標頭值,該值可安全地用於新舊瀏覽器。

Fallback name

  • 如果包含代碼小於 32 或大於 126 的非 ASCII 字元,則會導致問題。
  • 如果包含 URL 編碼字元(以 % 開頭)或 % 字元,則會導致問題。某些瀏覽器將 filename="X" 解釋為 URL 編碼名稱,有些則不這樣做。
  • 如果包含路徑分隔符字元,例如 \/,則會導致問題。
  • 由於值以 " 包裹,因此應逸出為 \"
  • 由於輸入可能包含非 ASCII 字元,因此透過音譯取得 fallback。

UTF 名稱

  • 如果包含路徑分隔符字元,例如 \/,則會導致問題。
  • 由於標頭僅限 ASCII,因此應進行 URL 編碼。
  • 如果與 fallback 名稱完全匹配,則可以省略。
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

傳回標頭集合。

Header 集合包含目前已註冊的 HTTP 標頭。

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

Header 集合

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

            
getHttpRange() protected method

決定請求中給定的 HTTP 範圍。

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

將用於驗證請求的 HTTP 範圍的檔案大小。

return array|boolean

範圍 (begin, end),如果範圍請求無效則為 false。

                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 布林值

此回應是否表示用戶端錯誤

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

            
getIsEmpty() public method

public boolean getIsEmpty ( )
return 布林值

此回應是否為空

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

            
getIsForbidden() public method

public boolean getIsForbidden ( )
return 布林值

此回應是否表示目前請求被禁止

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

            
getIsInformational() public method

public boolean getIsInformational ( )
return 布林值

此回應是否為資訊性

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

            
getIsInvalid() public method

public boolean getIsInvalid ( )
return 布林值

此回應是否具有有效的 $statusCode

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

            
getIsNotFound() public method

public boolean getIsNotFound ( )
return 布林值

此回應是否表示目前請求的資源未找到

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

            
getIsOk() public method

public boolean getIsOk ( )
return 布林值

此回應是否為 OK

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

            
getIsRedirection() public method

public boolean getIsRedirection ( )
return 布林值

此回應是否為重新導向

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

            
getIsServerError() public method

public boolean getIsServerError ( )
return 布林值

此回應是否表示伺服器錯誤

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

            
getIsSuccessful() public method

public boolean getIsSuccessful ( )
return 布林值

此回應是否成功

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

            
getStatusCode() public method

public integer getStatusCode ( )
return integer

隨回應發送的 HTTP 狀態碼。

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

            
hasEventHandlers() public method

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

傳回一個值,指示是否有名稱事件附加任何處理常式。

public boolean hasEventHandlers ( $name )
$name string

Event name

return 布林值

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

傳回一個值,指示是否已定義方法。

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

屬性名稱

$checkBehaviors 布林值

Whether to treat behaviors' methods as methods of this component

return 布林值

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

傳回一個值,指示是否為此元件定義屬性。

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);
  • 類別具有具有指定名稱的成員變數(當 $checkVars 為 true 時);
  • an attached behavior has a property of the given name (when $checkBehaviors is true).

另請參閱

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

屬性名稱

$checkVars 布林值

是否將成員變數視為屬性

$checkBehaviors 布林值

是否將行為的屬性視為此元件的屬性

return 布林值

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

初始化此元件。

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

從此元件分離現有的事件處理常式。

此方法與 on() 方法相反。

請注意:如果為事件名稱傳遞了萬用字元模式,則只會移除使用此萬用字元註冊的處理程式,而使用與此萬用字元匹配的純名稱註冊的處理程式將會保留。

另請參閱 on()

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

事件名稱

$handler callable|null

要移除的事件處理程式。如果為 null,則會移除附加到具名事件的所有處理程式。

return 布林值

如果找到並分離處理程式

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

將事件處理常式附加到事件。

事件處理程式必須是有效的 PHP 回呼。以下是一些範例

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

事件處理程式必須使用以下簽章定義,

function ($event)

其中 $event 是一個 yii\base\Event 物件,其中包含與事件關聯的參數。

自 2.0.14 版起,您可以將事件名稱指定為萬用字元模式

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

另請參閱 off()

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

Event name

$handler callable

事件處理程式

$data mixed

事件觸發時要傳遞給事件處理程式的資料。調用事件處理程式時,可以透過 yii\base\Event::$data 存取此資料。

$append 布林值

是否將新的事件處理程式附加到現有處理程式列表的末尾。如果為 false,則新的處理程式將插入到現有處理程式列表的開頭。

                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

準備發送回應。

預設實作會將 $data 轉換為 $content 並相應地設定標頭。

另請參閱

protected void prepare ( )
throws yii\base\InvalidConfigException

如果指定格式的格式器無效或不支援 $format 則會拋出此例外

                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

將瀏覽器重新導向到指定的 URL。

此方法會將 "Location" 標頭新增至目前回應。請注意,在呼叫 send() 之前,它不會傳送標頭。在控制器動作中,您可以如下使用此方法

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

在其他地方,如果您想立即傳送 "Location" 標頭,則應使用以下程式碼

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

在 AJAX 模式下,除非有一些用戶端 JavaScript 程式碼處理重新導向,否則這通常不會如預期般運作。為了協助實現此目標,此方法將傳送 "X-Redirect" 標頭而不是 "Location"。

如果您使用 "yii" JavaScript 模組,它將如上所述處理 AJAX 重新導向。否則,您應該編寫以下 JavaScript 程式碼來處理重新導向

$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

要重新導向到的 URL。這可以是以下格式之一

  • 表示 URL 的字串 (例如 "https://example.com")
  • 表示 URL 別名的字串 (例如 "@example.com")
  • 格式為 [$route, ...name-value pairs...] 的陣列 (例如:['site/index', 'ref' => 1])。請注意,路由是相對於整個應用程式,而不是相對於控制器或模組。yii\helpers\Url::to() 將用於將陣列轉換為 URL。

任何以單個正斜線 "/" 開頭的相對 URL,都會被轉換為絕對 URL,方法是在其前面加上當前請求的主機資訊。

$statusCode integer

HTTP 狀態碼。預設為 302。請參閱 https://tools.ietf.org/html/rfc2616#section-10 以取得關於 HTTP 狀態碼的詳細資訊

$checkAjax 布林值

是否特別處理 AJAX (和 PJAX) 請求。預設為 true,表示如果當前請求是 AJAX 或 PJAX 請求,則呼叫此方法將導致瀏覽器重新導向到給定的 URL。如果此值為 false,將會發送一個 Location 標頭,當作為 AJAX/PJAX 回應接收時,可能不會導致瀏覽器重新導向。僅在缺少請求標頭 X-Ie-Redirect-Compatibility 時生效。

return $this

回應物件本身

                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) {
        if (preg_match('/\n/', $normalizedUrl)) {
            throw new InvalidRouteException('Route with new line character detected "' . $normalizedUrl . '".');
        }
        if (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

重新整理目前頁面。

此方法呼叫的效果與使用者按下瀏覽器的重新整理按鈕 (不重新發布資料) 相同。

在控制器動作中,您可以像這樣使用此方法

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

應附加到重新導向 URL 的錨點。預設為空字串。如果您想指定錨點,請確保錨點以 '#' 開頭。

return yii\web\Response

回應物件本身

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

            
send() public method

將回應發送到用戶端。

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

將回應內容發送到用戶端。

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

將指定的內容作為檔案傳送到瀏覽器。

請注意,此方法僅準備回應以進行檔案傳送。檔案在 send() 被明確或隱含地呼叫之前不會被傳送。後者會在您從控制器動作返回後完成。

另請參閱 sendFile() 以取得範例實作。

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

要傳送的內容。現有的 $content 將被丟棄。

$attachmentName string

向使用者顯示的檔案名稱。

$options array

用於傳送檔案的其他選項。支援以下選項

  • mimeType:內容的 MIME 類型。預設為 'application/octet-stream'。
  • inline:布林值,表示瀏覽器是否應在瀏覽器視窗中開啟檔案。預設為 false,表示將彈出下載對話方塊。
return $this

回應物件本身

throws yii\web\RangeNotSatisfiableHttpException

如果請求的範圍無法滿足

                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

將 Cookie 發送到用戶端。

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;
        $expire = $cookie->expire;
        if (is_string($expire)) {
            $expire = strtotime($expire);
        } elseif (interface_exists('\\DateTimeInterface') && $expire instanceof \DateTimeInterface) {
            $expire = $expire->getTimestamp();
        }
        if ($expire === null || $expire === false) {
            $expire = 0;
        }
        if ($expire != 1 && isset($validationKey)) {
            $value = Yii::$app->getSecurity()->hashData(serialize([$cookie->name, $value]), $validationKey);
        }
        if (PHP_VERSION_ID >= 70300) {
            setcookie($cookie->name, $value, [
                'expires' => $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, $expire, $cookiePath, $cookie->domain, $cookie->secure, $cookie->httpOnly);
        }
    }
}

            
sendFile() public method

將檔案傳送到瀏覽器。

請注意,此方法僅準備回應以進行檔案傳送。檔案在 send() 被明確或隱含地呼叫之前不會被傳送。後者會在您從控制器動作返回後完成。

以下是一個控制器動作的範例實作,允許從無法從 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);
}

另請參閱

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

要傳送的檔案路徑。

$attachmentName string|null

向使用者顯示的檔案名稱。如果為 null,將從 $filePath 確定。

$options array

用於傳送檔案的其他選項。支援以下選項

  • mimeType:內容的 MIME 類型。如果未設定,將根據 $filePath 猜測
  • inline:布林值,表示瀏覽器是否應在瀏覽器視窗中開啟檔案。預設為 false,表示將彈出下載對話方塊。
return $this

回應物件本身

                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

將回應標頭發送到用戶端。

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

將指定的串流作為檔案傳送到瀏覽器。

請注意,此方法僅準備回應以進行檔案傳送。檔案在 send() 被明確或隱含地呼叫之前不會被傳送。後者會在您從控制器動作返回後完成。

另請參閱 sendFile() 以取得範例實作。

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

要傳送的串流的句柄。

$attachmentName string

向使用者顯示的檔案名稱。

$options array

用於傳送檔案的其他選項。支援以下選項

  • mimeType:內容的 MIME 類型。預設為 'application/octet-stream'。
  • inline:布林值,表示瀏覽器是否應在瀏覽器視窗中開啟檔案。預設為 false,表示將彈出下載對話方塊。
  • fileSize:要串流的內容大小。當內容大小已知且內容不可搜尋時,此選項很有用。預設為使用 ftell() 的內容大小。此選項自 2.0.4 版本起可用。
return $this

回應物件本身

throws yii\web\RangeNotSatisfiableHttpException

如果請求的範圍無法滿足

                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

為檔案下載目的設定一組預設的 HTTP 標頭。

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

附件檔案名稱

$mimeType string|null

回應的 MIME 類型。如果為 null,則不會設定 Content-Type 標頭。

$inline 布林值

瀏覽器是否應在瀏覽器視窗中開啟檔案。預設為 false,表示將彈出下載對話方塊。

$contentLength integer|null

正在下載的檔案的位元組長度。如果為 null,則不會設定 Content-Length 標頭。

return $this

回應物件本身

                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

設定回應狀態碼。

如果 $text 為 null,此方法將設定對應的狀態文字。

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

狀態碼

$text string|null

狀態文字。如果未設定,將根據狀態碼自動設定。

return $this

回應物件本身

throws yii\base\InvalidArgumentException

如果狀態碼無效。

                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 (自 2.0.12 版本起可用)

根據例外設定回應狀態碼。

public $this setStatusCodeByException ( $e )
$e Throwable

例外物件。

return $this

回應物件本身

throws yii\base\InvalidArgumentException

如果狀態碼無效。

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

            
trigger() public method

定義於: yii\base\Component::trigger()

觸發事件。

此方法表示事件的發生。它會調用事件的所有附加處理常式,包括類別層級的處理常式。

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

Event name

$event yii\base\Event|null

事件實例。如果未設定,將建立預設的 yii\base\Event 物件。

                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

使用 x-sendfile 將現有檔案作為下載傳送到瀏覽器。

X-Sendfile 是一個功能,允許 Web 應用程式將檔案請求重新導向到 Web 伺服器,然後由 Web 伺服器處理請求,從而無需執行讀取檔案並將其發送給使用者等任務。當處理大量檔案 (或非常大的檔案) 時,這可以大大提高效能,因為 Web 應用程式可以在 Web 伺服器處理請求時更早終止。

請求通過特殊的非標準 HTTP 標頭發送到伺服器。當 Web 伺服器遇到此類標頭時,它將丟棄所有輸出,並使用 Web 伺服器內部組件 (包括所有最佳化,如快取標頭) 發送該標頭指定的檔案。

由於此標頭指令是非標準的,因此不同的 Web 伺服器應用程式存在不同的指令

因此,為了使此方法有效,Web 伺服器應啟用 X-SENDFILE 選項/模組,並發送正確的 xHeader。

注意

此選項允許下載不在 Web 資料夾下的檔案,甚至允許下載其他受保護的檔案 (拒絕所有存取),例如 .htaccess

副作用

如果 Web 伺服器停用了此選項,則在呼叫此方法時,將開啟下載設定對話方塊,但下載的檔案將為 0 位元組。

已知問題

當通過 SSL 連接使用 X-SENDFILE 時,Internet Explorer 6、7 和 8 存在錯誤,它將顯示如下錯誤訊息:「Internet Explorer 無法開啟此 Internet 網站。要求的網站不可用或找不到。」。您可以通過移除 Pragma 標頭來解決此問題。

範例

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

另請參閱 sendFile()

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

具有完整路徑的檔案名稱

$attachmentName string|null

向使用者顯示的檔案名稱。如果為 null,將從 $filePath 確定。

$options array

用於傳送檔案的其他選項。支援以下選項

  • mimeType:內容的 MIME 類型。如果未設定,將根據 $filePath 猜測
  • inline:布林值,表示瀏覽器是否應在瀏覽器視窗中開啟檔案。預設為 false,表示將彈出下載對話方塊。
  • xHeader: string,x-sendfile 標頭的名稱。預設為 "X-Sendfile"。
return $this

回應物件本身

                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_AFTER_PREPARE event of type yii\base\Event

send() 中呼叫 prepare() 後立即觸發的事件。您可以回應此事件,以在回應內容發送到用戶端之前對其進行篩選。

EVENT_AFTER_SEND event of type yii\base\Event

send() 結束時觸發的事件。

EVENT_BEFORE_SEND event of type yii\base\Event

send() 開始時觸發的事件。