0 追蹤者

類別 yii\filters\HostControl

繼承關係yii\filters\HostControl » yii\base\ActionFilter » yii\base\Behavior » yii\base\BaseObject
實作介面yii\base\Configurable
自版本起可用2.0.11
原始碼 https://github.com/yiisoft/yii2/blob/master/framework/filters/HostControl.php

HostControl 提供了對請求主機名稱的簡單控制。

此篩選器提供針對 'Host 標頭' 攻擊的保護,僅允許對指定的主機名稱執行操作。

應用程式配置範例

return [
    'as hostControl' => [
        'class' => 'yii\filters\HostControl',
        'allowedHosts' => [
            'example.com',
            '*.example.com',
        ],
    ],
    // ...
];

控制器配置範例

use yii\web\Controller;
use yii\filters\HostControl;

class SiteController extends Controller
{
    public function behaviors()
    {
        return [
            'hostControl' => [
                'class' => HostControl::class,
                'allowedHosts' => [
                    'example.com',
                    '*.example.com',
                ],
            ],
        ];
    }

    // ...
}

注意:限制允許的主機名稱的最佳方式是使用 Web 伺服器的「虛擬主機」配置。此篩選器僅應在無法使用或配置遭洩露時使用。

公開屬性

隱藏繼承的屬性

屬性 類型 描述 定義於
$allowedHosts array|Closure|null 允許的主機名稱列表。 yii\filters\HostControl
$denyCallback callable|null 如果目前的 host 與 $allowedHosts 不符時,將會呼叫的回呼函數。 yii\filters\HostControl
$except array 此篩選器不應套用的動作 ID 清單。 yii\base\ActionFilter
$fallbackHostInfo string|null Request::$hostInfo 無效時,使用的備用 host 資訊 (例如 https://yii.dev.org.tw)。 yii\filters\HostControl
$only array 此篩選器應套用的動作 ID 清單。 yii\base\ActionFilter
$owner yii\base\Component|null 此行為的擁有者 yii\base\Behavior

Public Methods

Hide inherited methods

Method 描述 定義於
__call() 呼叫未定義為類別方法的具名方法。 yii\base\BaseObject
__construct() 建構子。 yii\base\BaseObject
__get() 傳回物件屬性的值。 yii\base\BaseObject
__isset() 檢查屬性是否已設定,亦即已定義且非 null。 yii\base\BaseObject
__set() 設定物件屬性的值。 yii\base\BaseObject
__unset() 將物件屬性設定為 null。 yii\base\BaseObject
afterAction() 此方法在動作執行完成後立即被呼叫。 yii\base\ActionFilter
afterFilter() yii\base\ActionFilter
attach() 將行為物件附加到元件。 yii\base\ActionFilter
beforeAction() 此方法在動作即將執行前(在所有可能的篩選器之後)被呼叫。您可以覆寫此方法,為動作進行最後一刻的準備。 yii\filters\HostControl
beforeFilter() yii\base\ActionFilter
canGetProperty() 傳回一個值,指出屬性是否可讀取。 yii\base\BaseObject
canSetProperty() 傳回一個值,指出屬性是否可設定。 yii\base\BaseObject
className() 傳回此類別的完整限定名稱。 yii\base\BaseObject
detach() 從元件卸離行為物件。 yii\base\ActionFilter
events() 宣告 $owner 事件的事件處理器。 yii\base\Behavior
hasMethod() 傳回一個值,指出方法是否已定義。 yii\base\BaseObject
hasProperty() 傳回一個值,指出屬性是否已定義。 yii\base\BaseObject
init() 初始化物件。 yii\base\BaseObject

Protected Methods

Hide inherited methods

Method 描述 定義於
denyAccess() 拒絕存取。 yii\filters\HostControl
getActionId() 透過將 yii\base\Action::$uniqueId 轉換為相對於模組的 ID,傳回動作 ID。 yii\base\ActionFilter
isActive() 傳回一個值,指出篩選器是否對給定的動作啟用。 yii\base\ActionFilter

Property Details

隱藏繼承的屬性

$allowedHosts public property

允許的 host 名稱清單。每個 host 可以指定為萬用字元模式。例如

[
    'example.com',
    '*.example.com',
]

此欄位可以指定為具有以下簽章的 PHP 回呼函數

function (\yii\base\Action $action) {
    //return array of strings
}

其中 $action 是目前的 action 物件。

如果未設定此欄位,則不會執行 host 名稱檢查。

$denyCallback public property

如果目前的 host 與 $allowedHosts 不符時,將會呼叫的回呼函數。如果未設定,則會呼叫 denyAccess()

回呼函數的簽章應如下所示

function (\yii\base\Action $action)

其中 $action 是目前的 action 物件。

注意:在實作您自己的 host 拒絕處理時,請確保您避免使用目前請求的 host 名稱、建立絕對 URL 連結、快取頁面部分等等。

public callable|null $denyCallback null
$fallbackHostInfo public property

Request::$hostInfo 無效時,使用的備用 host 資訊 (例如 https://yii.dev.org.tw)。此值將在呼叫 $denyCallback 之前取代 Request::$hostInfo,以確保無效的 host 不會用於進一步處理。您可以將其設定為 null 以保持 Request::$hostInfo 不變。預設值為空字串(這將導致建立相對 URL 而非絕對 URL)。

另請參閱 yii\web\Request::getHostInfo()

Method Details

Hide inherited methods

__call() public method

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

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

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

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

方法名稱

$params array

方法參數

return mixed

方法的傳回值

throws yii\base\UnknownMethodException

當呼叫未知方法時

                public function __call($name, $params)
{
    throw new UnknownMethodException('Calling unknown method: ' . get_class($this) . "::$name()");
}

            
__construct() public method

Defined in: 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 method

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

傳回物件屬性的值。

請勿直接呼叫此方法,因為它是一個 PHP 魔術方法,當執行 $value = $object->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)) {
        return $this->$getter();
    } elseif (method_exists($this, 'set' . $name)) {
        throw new InvalidCallException('Getting write-only property: ' . get_class($this) . '::' . $name);
    }
    throw new UnknownPropertyException('Getting unknown property: ' . get_class($this) . '::' . $name);
}

            
__isset() public method

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

檢查屬性是否已設定,亦即已定義且非 null。

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

請注意,如果屬性未定義,將會傳回 false。

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

public boolean __isset ( $name )
$name string

屬性名稱或事件名稱

return boolean

具名屬性是否已設定(非 null)。

                public function __isset($name)
{
    $getter = 'get' . $name;
    if (method_exists($this, $getter)) {
        return $this->$getter() !== null;
    }
    return false;
}

            
__set() public method

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

設定物件屬性的值。

請勿直接呼叫此方法,因為它是一個 PHP 魔術方法,當執行 $object->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)) {
        $this->$setter($value);
    } elseif (method_exists($this, 'get' . $name)) {
        throw new InvalidCallException('Setting read-only property: ' . get_class($this) . '::' . $name);
    } else {
        throw new UnknownPropertyException('Setting unknown property: ' . get_class($this) . '::' . $name);
    }
}

            
__unset() public method

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

將物件屬性設定為 null。

請勿直接呼叫此方法,因為它是一個 PHP 魔術方法,當執行 unset($object->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);
    } elseif (method_exists($this, 'get' . $name)) {
        throw new InvalidCallException('Unsetting read-only property: ' . get_class($this) . '::' . $name);
    }
}

            
afterAction() public method

Defined in: yii\base\ActionFilter::afterAction()

此方法在動作執行完成後立即被呼叫。

您可以覆寫此方法,為動作執行一些後處理。

public mixed afterAction ( $action, $result )
$action yii\base\Action

剛執行的動作。

$result mixed

動作執行結果

return mixed

已處理的動作結果。

                public function afterAction($action, $result)
{
    return $result;
}

            
afterFilter() public method
public void afterFilter ( $event )
$event yii\base\ActionEvent

                public function afterFilter($event)
{
    $event->result = $this->afterAction($event->action, $event->result);
    $this->owner->off(Controller::EVENT_AFTER_ACTION, [$this, 'afterFilter']);
}

            
attach() public method

Defined in: yii\base\ActionFilter::attach()

將行為物件附加到元件。

預設實作將設定 $owner 屬性,並附加在 events() 中宣告的事件處理器。如果您覆寫此方法,請確保呼叫父類別的實作。

public void attach ( $owner )
$owner yii\base\Component

此行為要附加到的元件。

                public function attach($owner)
{
    $this->owner = $owner;
    $owner->on(Controller::EVENT_BEFORE_ACTION, [$this, 'beforeFilter']);
}

            
beforeAction() public method

此方法在動作即將執行前(在所有可能的篩選器之後)被呼叫。您可以覆寫此方法,為動作進行最後一刻的準備。

public boolean beforeAction ( $action )
$action yii\base\Action

要執行的動作。

return boolean

是否應繼續執行動作。

                public function beforeAction($action)
{
    $allowedHosts = $this->allowedHosts;
    if ($allowedHosts instanceof \Closure) {
        $allowedHosts = call_user_func($allowedHosts, $action);
    }
    if ($allowedHosts === null) {
        return true;
    }
    if (!is_array($allowedHosts) && !$allowedHosts instanceof \Traversable) {
        $allowedHosts = (array) $allowedHosts;
    }
    $currentHost = Yii::$app->getRequest()->getHostName();
    foreach ($allowedHosts as $allowedHost) {
        if (StringHelper::matchWildcard($allowedHost, $currentHost)) {
            return true;
        }
    }
    // replace invalid host info to prevent using it in further processing
    if ($this->fallbackHostInfo !== null) {
        Yii::$app->getRequest()->setHostInfo($this->fallbackHostInfo);
    }
    if ($this->denyCallback !== null) {
        call_user_func($this->denyCallback, $action);
    } else {
        $this->denyAccess($action);
    }
    return false;
}

            
beforeFilter() public method
public void beforeFilter ( $event )
$event yii\base\ActionEvent

                public function beforeFilter($event)
{
    if (!$this->isActive($event->action)) {
        return;
    }
    $event->isValid = $this->beforeAction($event->action);
    if ($event->isValid) {
        // call afterFilter only if beforeFilter succeeds
        // beforeFilter and afterFilter should be properly nested
        $this->owner->on(Controller::EVENT_AFTER_ACTION, [$this, 'afterFilter'], null, false);
    } else {
        $event->handled = true;
    }
}

            
canGetProperty() public method

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

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

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

  • 類別具有與指定名稱相關聯的 getter 方法(在此情況下,屬性名稱不區分大小寫);
  • 類別具有具有指定名稱的成員變數(當 $checkVars 為 true 時);

另請參閱 canSetProperty()

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

屬性名稱

$checkVars boolean

是否將成員變數視為屬性

return boolean

屬性是否可讀取

                public function canGetProperty($name, $checkVars = true)
{
    return method_exists($this, 'get' . $name) || $checkVars && property_exists($this, $name);
}

            
canSetProperty() public method

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

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

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

  • 類別具有與指定名稱相關聯的 setter 方法(在此情況下,屬性名稱不區分大小寫);
  • 類別具有具有指定名稱的成員變數(當 $checkVars 為 true 時);

另請參閱 canGetProperty()

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

屬性名稱

$checkVars boolean

是否將成員變數視為屬性

return boolean

屬性是否可寫入

                public function canSetProperty($name, $checkVars = true)
{
    return method_exists($this, 'set' . $name) || $checkVars && property_exists($this, $name);
}

            
className() public static method
自 2.0.14 版本起已棄用。在 PHP >=5.5 上,請改用 ::class

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

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

public static string className ( )
return string

此類別的完整限定名稱。

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

            
denyAccess() protected method

拒絕存取。

預設實作會立即顯示 404 頁面,終止程式執行。您可以覆寫此方法,建立您自己的拒絕存取處理常式。這樣做時,請確保您避免使用目前請求的 host 名稱、建立絕對 URL 連結、快取頁面部分等等。

protected void denyAccess ( $action )
$action yii\base\Action

要執行的動作。

throws yii\web\NotFoundHttpException

                protected function denyAccess($action)
{
    $exception = new NotFoundHttpException(Yii::t('yii', 'Page not found.'));
    // use regular error handling if $this->fallbackHostInfo was set
    if (!empty(Yii::$app->getRequest()->hostName)) {
        throw $exception;
    }
    $response = Yii::$app->getResponse();
    $errorHandler = Yii::$app->getErrorHandler();
    $response->setStatusCode($exception->statusCode, $exception->getMessage());
    $response->data = $errorHandler->renderFile($errorHandler->errorView, ['exception' => $exception]);
    $response->send();
    Yii::$app->end();
}

            
detach() public method

Defined in: yii\base\ActionFilter::detach()

從元件卸離行為物件。

預設實作將取消設定 $owner 屬性,並卸離在 events() 中宣告的事件處理器。如果您覆寫此方法,請確保呼叫父類別的實作。

public void detach ( )

                public function detach()
{
    if ($this->owner) {
        $this->owner->off(Controller::EVENT_BEFORE_ACTION, [$this, 'beforeFilter']);
        $this->owner->off(Controller::EVENT_AFTER_ACTION, [$this, 'afterFilter']);
        $this->owner = null;
    }
}

            
events() public method

Defined in: yii\base\Behavior::events()

宣告 $owner 事件的事件處理器。

子類別可以覆寫此方法,以宣告應將哪些 PHP 回呼函數附加到 $owner 元件的事件。

當行為附加到擁有者時,回呼函數將附加到 $owner 的事件;當行為從元件卸離時,它們將從事件中卸離。

回呼函數可以是以下任何一種

  • 此行為中的方法:'handleClick',等同於 [$this, 'handleClick']
  • 物件方法:[$object, 'handleClick']
  • 靜態方法:['Page', 'handleClick']
  • 匿名函數:function ($event) { ... }

以下是一個範例

[
    Model::EVENT_BEFORE_VALIDATE => 'myBeforeValidate',
    Model::EVENT_AFTER_VALIDATE => 'myAfterValidate',
]
public array events ( )
return array

事件(陣列鍵)和對應的事件處理器方法(陣列值)。

                public function events()
{
    return [];
}

            
getActionId() protected method (available since version 2.0.7)

Defined in: yii\base\ActionFilter::getActionId()

透過將 yii\base\Action::$uniqueId 轉換為相對於模組的 ID,傳回動作 ID。

protected string getActionId ( $action )
$action yii\base\Action

                protected function getActionId($action)
{
    if ($this->owner instanceof Module) {
        $mid = $this->owner->getUniqueId();
        $id = $action->getUniqueId();
        if ($mid !== '' && strpos($id, $mid) === 0) {
            $id = substr($id, strlen($mid) + 1);
        }
    } else {
        $id = $action->id;
    }
    return $id;
}

            
hasMethod() public method

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

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

預設實作是對 php 函數 method_exists() 的呼叫。當您實作了 php 魔術方法 __call() 時,您可以覆寫此方法。

public boolean hasMethod ( $name )
$name string

方法名稱

return boolean

方法是否已定義

                public function hasMethod($name)
{
    return method_exists($this, $name);
}

            
hasProperty() public method

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

傳回一個值,指出屬性是否已定義。

如果符合以下條件,則屬性已定義

  • 類別具有與指定名稱相關聯的 getter 或 setter 方法(在此情況下,屬性名稱不區分大小寫);
  • 類別具有具有指定名稱的成員變數(當 $checkVars 為 true 時);

另請參閱

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

屬性名稱

$checkVars boolean

是否將成員變數視為屬性

return boolean

屬性是否已定義

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

            
init() public method

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

初始化物件。

在物件以給定的組態初始化之後,此方法會在建構子的結尾被呼叫。

public void init ( )

                public function init()
{
}

            
isActive() protected method

定義於: yii\base\ActionFilter::isActive()

傳回一個值,指出篩選器是否對給定的動作啟用。

protected boolean isActive ( $action )
$action yii\base\Action

正在被過濾的動作

return boolean

篩選器是否對給定的動作生效。

                protected function isActive($action)
{
    $id = $this->getActionId($action);
    if (empty($this->only)) {
        $onlyMatch = true;
    } else {
        $onlyMatch = false;
        foreach ($this->only as $pattern) {
            if (StringHelper::matchWildcard($pattern, $id)) {
                $onlyMatch = true;
                break;
            }
        }
    }
    $exceptMatch = false;
    foreach ($this->except as $pattern) {
        if (StringHelper::matchWildcard($pattern, $id)) {
            $exceptMatch = true;
            break;
        }
    }
    return !$exceptMatch && $onlyMatch;
}