1 追蹤者

類別 yii\web\Session

繼承關係yii\web\Session » yii\base\Component » yii\base\BaseObject
實作介面ArrayAccess, Countable, IteratorAggregate, yii\base\Configurable
子類別yii\web\CacheSession, yii\web\DbSession, yii\web\MultiFieldSession
自版本起可用2.0
原始碼 https://github.com/yiisoft/yii2/blob/master/framework/web/Session.php

Session 提供 session 資料管理和相關配置。

Session 是一個 Web 應用程式組件,可以透過 Yii::$app->session 存取。

若要開始 session,請呼叫 open();若要完成並發送 session 資料,請呼叫 close();若要銷毀 session,請呼叫 destroy()

Session 可以像陣列一樣使用來設定和取得 session 資料。例如:

$session = new Session;
$session->open();
$value1 = $session['name1'];  // get session variable 'name1'
$value2 = $session['name2'];  // get session variable 'name2'
foreach ($session as $name => $value) // traverse all session variables
$session['name3'] = $value3;  // set session variable 'name3'

Session 可以擴展以支援自訂 session 儲存。若要這樣做,請覆寫 $useCustomStorage 使其傳回 true,並覆寫這些方法以使用自訂儲存的實際邏輯:openSession()closeSession()readSession()writeSession()destroySession()gcSession()

Session 也支援一種特殊的 session 資料類型,稱為快閃訊息。快閃訊息僅在當前請求和下一個請求中可用。之後,它將自動刪除。快閃訊息對於顯示確認訊息特別有用。若要使用快閃訊息,只需呼叫諸如 setFlash()getFlash() 等方法。

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

公開屬性

隱藏繼承的屬性

屬性 類型 描述 定義於
$_forceRegenerateId string|null 如果啟用 useStrictMode 且 session id 需要重新產生,則持有 session id yii\web\Session
$_originalSessionModule string|null 保留原始的 session 模組 (在自訂處理器註冊之前),以便在具有自訂處理器的 Session 元件之後使用沒有自訂處理器的 Session 元件時可以還原。 yii\web\Session
$allFlashes array Flash 訊息 (鍵 => 訊息 或 鍵 => [訊息1, 訊息2])。 yii\web\Session
$behaviors yii\base\Behavior[] 附加到此元件的行為列表。 yii\base\Component
$cacheLimiter string 目前的快取限制器。 yii\web\Session
$cookieParams array Session Cookie 參數。 yii\web\Session
$count integer Session 變數的數量。 yii\web\Session
$flash string 識別 Flash 訊息的鍵。 yii\web\Session
$flashParam string 儲存 Flash 訊息資料的 Session 變數名稱。 yii\web\Session
$gCProbability float 每次 session 初始化時啟動 GC (垃圾收集) 程序的機率 (百分比)。 yii\web\Session
$handler SessionHandlerInterface|array 實作 SessionHandlerInterface 的物件或組態陣列。 yii\web\Session
$hasSessionId boolean 目前請求是否已發送 session ID。 yii\web\Session
$id string 目前的 session ID。 yii\web\Session
$isActive boolean Session 是否已啟動。 yii\web\Session
$iterator yii\web\SessionIterator 用於遍歷 session 變數的迭代器。 yii\web\Session
$name string 目前的 session 名稱。 yii\web\Session
$savePath string 目前的 session 儲存路徑,預設為 '/tmp'。 yii\web\Session
$timeout integer 資料被視為「垃圾」並清除之前的秒數。 yii\web\Session
$useCookies boolean|null 指出是否應使用 Cookie 儲存 session ID 的值。 yii\web\Session
$useCustomStorage boolean 是否使用自訂儲存空間。 yii\web\Session
$useStrictMode boolean 是否啟用嚴格模式。 yii\web\Session
$useTransparentSessionID boolean 是否啟用透明 sid 支援,預設為 false。 yii\web\Session

受保護的屬性

隱藏繼承的屬性

屬性 類型 描述 定義於

公開方法

隱藏繼承的方法

方法 描述 定義於
__call() 呼叫指定的非類別方法。 yii\base\Component
__clone() 在透過複製現有物件建立新物件後,會呼叫此方法。 yii\base\Component
__construct() 建構子。 yii\base\BaseObject
__get() 傳回元件屬性的值。 yii\base\Component
__isset() 檢查屬性是否已設定,即已定義且非 null。 yii\base\Component
__set() 設定元件屬性的值。 yii\base\Component
__unset() 將元件屬性設定為 null。 yii\base\Component
addFlash() 新增一個 Flash 訊息。 yii\web\Session
attachBehavior() 將一個行為附加到此元件。 yii\base\Component
attachBehaviors() 將行為列表附加到元件。 yii\base\Component
behaviors() 傳回此元件應表現為的行為列表。 yii\base\Component
canGetProperty() 傳回一個值,指出屬性是否可以讀取。 yii\base\Component
canSetProperty() 傳回一個值,指出屬性是否可以設定。 yii\base\Component
className() 傳回此類別的完整限定名稱。 yii\base\BaseObject
close() 結束目前的 session 並儲存 session 資料。 yii\web\Session
count() 傳回 session 中的項目數量。 yii\web\Session
destroy() 釋放所有 session 變數並銷毀所有註冊到 session 的資料。 yii\web\Session
detachBehavior() 從元件中分離一個行為。 yii\base\Component
detachBehaviors() 從元件中分離所有行為。 yii\base\Component
ensureBehaviors() 確保在 behaviors() 中宣告的行為已附加到此元件。 yii\base\Component
get() 傳回具有指定 session 變數名稱的 session 變數值。 yii\web\Session
getAllFlashes() 傳回所有 Flash 訊息。 yii\web\Session
getBehavior() 傳回指定的行為物件。 yii\base\Component
getBehaviors() 傳回附加到此元件的所有行為。 yii\base\Component
getCacheLimiter() 傳回目前的快取限制器 yii\web\Session
getCookieParams() yii\web\Session
getCount() 傳回 session 中的項目數量。 yii\web\Session
getFlash() 傳回一個 Flash 訊息。 yii\web\Session
getGCProbability() yii\web\Session
getHasSessionId() 傳回一個值,指出目前請求是否已發送 session ID。 yii\web\Session
getId() 取得 session ID。 yii\web\Session
getIsActive() yii\web\Session
getIterator() 傳回一個用於遍歷 session 變數的迭代器。 yii\web\Session
getName() 取得目前 session 的名稱。 yii\web\Session
getSavePath() 取得目前的 session 儲存路徑。 yii\web\Session
getTimeout() yii\web\Session
getUseCookies() 傳回指出是否應使用 Cookie 儲存 session ID 的值。 yii\web\Session
getUseCustomStorage() 傳回一個值,指出是否使用自訂 session 儲存空間。 yii\web\Session
getUseStrictMode() yii\web\Session
getUseTransparentSessionID() yii\web\Session
has() yii\web\Session
hasEventHandlers() 傳回一個值,指出是否有任何處理器附加到指定的事件。 yii\base\Component
hasFlash() 傳回一個值,指出是否有名為指定鍵的 Flash 訊息。 yii\web\Session
hasMethod() 傳回一個值,指出是否已定義方法。 yii\base\Component
hasProperty() 傳回一個值,指出是否已為此元件定義屬性。 yii\base\Component
init() 初始化應用程式元件。 yii\web\Session
off() 從此元件分離現有的事件處理器。 yii\base\Component
offsetExists() 介面 ArrayAccess 要求此方法。 yii\web\Session
offsetGet() 介面 ArrayAccess 要求此方法。 yii\web\Session
offsetSet() 介面 ArrayAccess 要求此方法。 yii\web\Session
offsetUnset() 介面 ArrayAccess 要求此方法。 yii\web\Session
on() 將事件處理器附加到事件。 yii\base\Component
open() 啟動 session。 yii\web\Session
regenerateID() 使用新產生的 session ID 更新目前的 session ID。 yii\web\Session
remove() 移除一個 session 變數。 yii\web\Session
removeAll() 移除所有 session 變數。 yii\web\Session
removeAllFlashes() 移除所有 Flash 訊息。 yii\web\Session
removeFlash() 移除一個 Flash 訊息。 yii\web\Session
set() 新增一個 session 變數。 yii\web\Session
setCacheLimiter() 設定快取限制器 yii\web\Session
setCookieParams() 設定 Session Cookie 參數。 yii\web\Session
setFlash() 設定一個 Flash 訊息。 yii\web\Session
setGCProbability() yii\web\Session
setHasSessionId() 設定指出目前請求是否已發送 session ID 的值。 yii\web\Session
setId() 設定 session ID。 yii\web\Session
setName() 設定目前 session 的名稱。 yii\web\Session
setSavePath() 設定目前的 session 儲存路徑。 yii\web\Session
setTimeout() yii\web\Session
setUseCookies() 設定指出是否應使用 Cookie 儲存 session ID 的值。 yii\web\Session
setUseStrictMode() yii\web\Session
setUseTransparentSessionID() yii\web\Session
trigger() 觸發一個事件。 yii\base\Component

受保護的方法

隱藏繼承的方法

方法 描述 定義於
freeze() 如果 session 已啟動,則無法編輯 session ini 設定。在 PHP 7.2+ 版本中,這會拋出例外。 yii\web\Session
registerSessionHandler() 註冊 session 處理器。 yii\web\Session
unfreeze() 啟動 session 並從暫存變數還原資料 yii\web\Session
updateFlashCounters() 更新 Flash 訊息的計數器並移除過期的 Flash 訊息。 yii\web\Session

屬性詳細資料

隱藏繼承的屬性

$_forceRegenerateId 受保護的屬性

如果啟用 useStrictMode 且 session id 需要重新產生,則持有 session id

protected string|null $_forceRegenerateId null
$_originalSessionModule 受保護的靜態屬性

保留原始的 session 模組 (在自訂處理器註冊之前),以便在具有自訂處理器的 Session 元件之後使用沒有自訂處理器的 Session 元件時可以還原。

protected static string|null $_originalSessionModule null
$allFlashes 公開屬性

Flash 訊息 (鍵 => 訊息 或 鍵 => [訊息1, 訊息2])。

public array $allFlashes null
$cacheLimiter 公開屬性

目前的快取限制器。

public string $cacheLimiter null
$cookieParams 公開屬性

Session Cookie 參數。

public array $cookieParams null
$count 公開屬性

Session 變數的數量。

public integer $count null
$flash 公開屬性

識別 Flash 訊息的鍵。 請注意,Flash 訊息和一般 session 變數共用相同的命名空間。 如果您有一個使用相同名稱的一般 session 變數,其值將會被此方法覆寫。

public string $flash null
$flashParam 公開屬性

儲存 Flash 訊息資料的 Session 變數名稱。

public string $flashParam '__flash'
$gCProbability 公開屬性

每次 session 初始化時啟動 GC (垃圾收集) 程序的機率 (百分比)。

public float $gCProbability null
$handler 公開屬性

實作 SessionHandlerInterface 的物件或組態陣列。 如果設定,將用於提供持久性,而不是內建方法。

$hasSessionId 公開屬性

目前請求是否已發送 session ID。

public boolean $hasSessionId null
$id 公開屬性

目前的 session ID。

public string $id null
$isActive 公開屬性

Session 是否已啟動。

public boolean $isActive null
$iterator 公開唯讀屬性

用於遍歷 session 變數的迭代器。

$name 公開屬性

目前的 session 名稱。

public string $name null
$savePath 公開屬性

目前的 session 儲存路徑,預設為 '/tmp'。

public string $savePath null
$timeout 公開屬性

資料被視為「垃圾」並清除之前的秒數。 預設值為 1440 秒 (或 php.ini 中設定的 "session.gc_maxlifetime" 值)。

public integer $timeout null
$useCookies 公開屬性

指出是否應使用 Cookie 儲存 session ID 的值。

public boolean|null $useCookies null
$useCustomStorage 公開屬性

是否使用自訂儲存空間。

public boolean $useCustomStorage null
$useStrictMode 公開屬性

是否啟用嚴格模式。

public boolean $useStrictMode null
$useTransparentSessionID 公開屬性

是否啟用透明 sid 支援,預設為 false。

方法詳細資料

隱藏繼承的方法

__call() 公開方法

定義於: 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() 公開方法

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

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

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

public void __clone ( )

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

            
__construct() 公開方法

定義於: 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() 公開方法

定義於: 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() 公開方法

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

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

此方法將依以下順序檢查並採取相應的動作

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

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

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

public boolean __isset ( $name )
$name string

屬性名稱或事件名稱

return boolean

具名屬性是否已設定

                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);
}

            
addFlash() public 方法

新增一個 Flash 訊息。

如果存在具有相同鍵的快閃訊息,新的訊息將會附加到現有的訊息陣列中。

另請參閱

public void addFlash ( $key, $value true, $removeAfterAccess true )
$key string

識別 Flash 訊息的鍵。

$value mixed

快閃訊息

$removeAfterAccess boolean

快閃訊息是否應僅在被存取後自動移除。如果為 false,則快閃訊息將在下一個請求後自動移除,無論是否被存取。如果為 true(預設值),則快閃訊息將保留到被存取之後。

                public function addFlash($key, $value = true, $removeAfterAccess = true)
{
    $counters = $this->get($this->flashParam, []);
    $counters[$key] = $removeAfterAccess ? -1 : 0;
    $_SESSION[$this->flashParam] = $counters;
    if (empty($_SESSION[$key])) {
        $_SESSION[$key] = [$value];
    } elseif (is_array($_SESSION[$key])) {
        $_SESSION[$key][] = $value;
    } else {
        $_SESSION[$key] = [$_SESSION[$key], $value];
    }
}

            
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 boolean

是否將成員變數視為屬性

$checkBehaviors boolean

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

return boolean

屬性是否可以被讀取

                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 boolean

是否將成員變數視為屬性

$checkBehaviors boolean

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

return boolean

屬性是否可以被寫入

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

            
close() public 方法

結束目前的 session 並儲存 session 資料。

public void close ( )

                public function close()
{
    if ($this->getIsActive()) {
        YII_DEBUG ? session_write_close() : @session_write_close();
    }
    $this->_forceRegenerateId = null;
}

            
count() public 方法

傳回 session 中的項目數量。

此方法為 Countable 介面所必需。

public integer count ( )
return integer

Session 中的項目數量。

                #[\ReturnTypeWillChange]
public function count()
{
    return $this->getCount();
}

            
destroy() public 方法

釋放所有 session 變數並銷毀所有註冊到 session 的資料。

當 session 不是 active 時,此方法無效。請確保在呼叫此方法之前先呼叫 open()

另請參閱

public void destroy ( )

                public function destroy()
{
    if ($this->getIsActive()) {
        $sessionId = session_id();
        $this->close();
        $this->setId($sessionId);
        $this->open();
        session_unset();
        session_destroy();
        $this->setId($sessionId);
    }
}

            
detachBehavior() public 方法

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

從元件中分離一個行為。

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

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

行為的名稱。

return yii\base\Behavior|null

已分離的行為。如果行為不存在,則為 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 方法

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

從元件中分離所有行為。

public void detachBehaviors ( )

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

            
ensureBehaviors() public 方法

定義於: 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);
        }
    }
}

            
freeze() protected 方法 (自版本 2.0.14 起可用)

如果 session 已啟動,則無法編輯 session ini 設定。在 PHP 7.2+ 版本中,這會拋出例外。

此函數將 session 資料儲存到暫時變數並停止 session。

protected void freeze ( )

                protected function freeze()
{
    if ($this->getIsActive()) {
        if (isset($_SESSION)) {
            $this->_frozenSessionData = $_SESSION;
        }
        $this->close();
        Yii::info('Session frozen', __METHOD__);
    }
}

            
get() public 方法

傳回具有指定 session 變數名稱的 session 變數值。

如果 session 變數不存在,將會傳回 $defaultValue

public mixed get ( $key, $defaultValue null )
$key string

Session 變數名稱

$defaultValue mixed

當 session 變數不存在時要傳回的預設值。

return mixed

Session 變數值,如果 session 變數不存在,則為 $defaultValue。

                public function get($key, $defaultValue = null)
{
    $this->open();
    return isset($_SESSION[$key]) ? $_SESSION[$key] : $defaultValue;
}

            
getAllFlashes() public 方法

傳回所有 Flash 訊息。

您可以使用此方法在檢視檔案中顯示所有快閃訊息

<?php
foreach (Yii::$app->session->getAllFlashes() as $key => $message) {
    echo '<div class="alert alert-' . $key . '">' . $message . '</div>';
} ?>

使用上述程式碼,您可以使用 bootstrap alert 類別,例如 successinfodanger 作為快閃訊息鍵,以影響 div 的顏色。

請注意,如果您使用 addFlash()$message 將會是一個陣列,您將必須調整上述程式碼。

另請參閱

public array getAllFlashes ( $delete false )
$delete boolean

是否在此方法呼叫後立即刪除快閃訊息。如果為 false,則快閃訊息將在下一個請求中自動刪除。

return array

Flash 訊息 (鍵 => 訊息 或 鍵 => [訊息1, 訊息2])。

                public function getAllFlashes($delete = false)
{
    $counters = $this->get($this->flashParam, []);
    $flashes = [];
    foreach (array_keys($counters) as $key) {
        if (array_key_exists($key, $_SESSION)) {
            $flashes[$key] = $_SESSION[$key];
            if ($delete) {
                unset($counters[$key], $_SESSION[$key]);
            } elseif ($counters[$key] < 0) {
                // mark for deletion in the next request
                $counters[$key] = 1;
            }
        } else {
            unset($counters[$key]);
        }
    }
    $_SESSION[$this->flashParam] = $counters;
    return $flashes;
}

            
getBehavior() public 方法

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

傳回指定的行為物件。

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

行為名稱

return yii\base\Behavior|null

行為物件,如果行為不存在,則為 null

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

            
getBehaviors() public 方法

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

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

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

附加到此元件的行為列表

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

            
getCacheLimiter() public 方法 (自版本 2.0.14 起可用)

傳回目前的快取限制器

public string getCacheLimiter ( )
return string

目前的快取限制器

                public function getCacheLimiter()
{
    return session_cache_limiter();
}

            
getCookieParams() public 方法
public array getCookieParams ( )
return array

Session Cookie 參數。

                public function getCookieParams()
{
    return array_merge(session_get_cookie_params(), array_change_key_case($this->_cookieParams));
}

            
getCount() public 方法

傳回 session 中的項目數量。

public integer getCount ( )
return integer

session 變數的數量

                public function getCount()
{
    $this->open();
    return count($_SESSION);
}

            
getFlash() public 方法

傳回一個 Flash 訊息。

另請參閱

public mixed getFlash ( $key, $defaultValue null, $delete false )
$key string

用於識別快閃訊息的鍵

$defaultValue mixed

如果快閃訊息不存在,則傳回的值。

$delete boolean

是否在此方法呼叫後立即刪除此快閃訊息。如果為 false,則快閃訊息將在下一個請求中自動刪除。

return mixed

快閃訊息,如果使用了 addFlash,則為訊息陣列

                public function getFlash($key, $defaultValue = null, $delete = false)
{
    $counters = $this->get($this->flashParam, []);
    if (isset($counters[$key])) {
        $value = $this->get($key, $defaultValue);
        if ($delete) {
            $this->removeFlash($key);
        } elseif ($counters[$key] < 0) {
            // mark for deletion in the next request
            $counters[$key] = 1;
            $_SESSION[$this->flashParam] = $counters;
        }
        return $value;
    }
    return $defaultValue;
}

            
getGCProbability() public 方法

public float getGCProbability ( )
return float

每次 session 初始化時啟動 GC (垃圾收集) 程序的機率 (百分比)。

                public function getGCProbability()
{
    return (float) (ini_get('session.gc_probability') / ini_get('session.gc_divisor') * 100);
}

            
getHasSessionId() public 方法

傳回一個值,指出目前請求是否已發送 session ID。

預設實作將使用 session 名稱檢查 cookie 和 $_GET。如果您透過其他方式傳送 session ID,您可能需要覆寫此方法或呼叫 setHasSessionId() 以明確設定是否已傳送 session ID。

public boolean getHasSessionId ( )
return boolean

目前請求是否已發送 session ID。

                public function getHasSessionId()
{
    if ($this->_hasSessionId === null) {
        $name = $this->getName();
        $request = Yii::$app->getRequest();
        if (!empty($_COOKIE[$name]) && ini_get('session.use_cookies')) {
            $this->_hasSessionId = true;
        } elseif (!ini_get('session.use_only_cookies') && ini_get('session.use_trans_sid')) {
            $this->_hasSessionId = $request->get($name) != '';
        } else {
            $this->_hasSessionId = false;
        }
    }
    return $this->_hasSessionId;
}

            
getId() public 方法

取得 session ID。

這是 PHP session_id() 的包裝器。

public string getId ( )
return string

目前的 session ID

                public function getId()
{
    return session_id();
}

            
getIsActive() public 方法

public boolean getIsActive ( )
return boolean

Session 是否已啟動

                public function getIsActive()
{
    return session_status() === PHP_SESSION_ACTIVE;
}

            
getIterator() public method

傳回一個用於遍歷 session 變數的迭代器。

此方法為介面 IteratorAggregate 所需。

public yii\web\SessionIterator getIterator ( )
return yii\web\SessionIterator

用於遍歷 session 變數的迭代器。

                #[\ReturnTypeWillChange]
public function getIterator()
{
    $this->open();
    return new SessionIterator();
}

            
getName() public method

取得目前 session 的名稱。

這是 PHP session_name() 的包裝器。

public string getName ( )
return string

目前的 session 名稱

                public function getName()
{
    return session_name();
}

            
getSavePath() public method

取得目前的 session 儲存路徑。

這是 PHP session_save_path() 的包裝器。

public string getSavePath ( )
return string

目前的 session 儲存路徑,預設為 '/tmp'。

                public function getSavePath()
{
    return session_save_path();
}

            
getTimeout() public method

public integer getTimeout ( )
return integer

資料被視為「垃圾」並清除之前的秒數。 預設值為 1440 秒 (或 php.ini 中設定的 "session.gc_maxlifetime" 值)。

                public function getTimeout()
{
    return (int) ini_get('session.gc_maxlifetime');
}

            
getUseCookies() public method

傳回指出是否應使用 Cookie 儲存 session ID 的值。

另請參閱 setUseCookies()

public boolean|null getUseCookies ( )
return boolean|null

指出是否應使用 Cookie 儲存 session ID 的值。

                public function getUseCookies()
{
    if (ini_get('session.use_cookies') === '0') {
        return false;
    } elseif (ini_get('session.use_only_cookies') === '1') {
        return true;
    }
    return null;
}

            
getUseCustomStorage() public method

傳回一個值,指出是否使用自訂 session 儲存空間。

子類別實作自訂 session 儲存時,應覆寫此方法以回傳 true。若要實作自訂 session 儲存,請覆寫這些方法: openSession()closeSession()readSession()writeSession()destroySession()gcSession()

public boolean getUseCustomStorage ( )
return boolean

是否使用自訂儲存空間。

                public function getUseCustomStorage()
{
    return false;
}

            
getUseStrictMode() public method (自 2.0.38 版本起可用)

另請參閱 setUseStrictMode()

public boolean getUseStrictMode ( )
return boolean

是否啟用嚴格模式。

                public function getUseStrictMode()
{
    if (PHP_VERSION_ID < 50502) {
        return self::$_useStrictModePolyfill;
    }
    return (bool)ini_get('session.use_strict_mode');
}

            
getUseTransparentSessionID() public method

public boolean getUseTransparentSessionID ( )
return boolean

是否啟用透明 sid 支援,預設為 false。

                public function getUseTransparentSessionID()
{
    return ini_get('session.use_trans_sid') == 1;
}

            
has() public method

public boolean has ( $key )
$key mixed

Session 變數名稱

return boolean

是否有指定的 session 變數

                public function has($key)
{
    $this->open();
    return isset($_SESSION[$key]);
}

            
hasEventHandlers() public method

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

傳回一個值,指出是否有任何處理器附加到指定的事件。

public boolean hasEventHandlers ( $name )
$name string

事件名稱

return boolean

是否有任何處理器附加到事件。

                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);
}

            
hasFlash() public method

傳回一個值,指出是否有名為指定鍵的 Flash 訊息。

public boolean hasFlash ( $key )
$key string

識別快閃訊息類型的鍵

return boolean

在指定的鍵下是否存在任何快閃訊息

                public function hasFlash($key)
{
    return $this->getFlash($key) !== null;
}

            
hasMethod() public method

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

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

方法已定義如果

  • 類別具有指定名稱的方法
  • 附加的行為具有給定名稱的方法 (當 $checkBehaviors 為 true 時)。
public boolean hasMethod ( $name, $checkBehaviors true )
$name string

屬性名稱

$checkBehaviors boolean

是否將行為的方法視為此組件的方法

return boolean

方法是否已定義

                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

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

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

屬性已定義如果

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

另請參閱

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

屬性名稱

$checkVars boolean

是否將成員變數視為屬性

$checkBehaviors boolean

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

return boolean

屬性是否已定義

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

            
init() public method

初始化應用程式元件。

此方法為 IApplicationComponent 所需,並由應用程式調用。

public void init ( )

                public function init()
{
    parent::init();
    register_shutdown_function([$this, 'close']);
    if ($this->getIsActive()) {
        Yii::warning('Session is already started', __METHOD__);
        $this->updateFlashCounters();
    }
}

            
off() public method

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

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

此方法與 on() 相反。

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

另請參閱 on()

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

事件名稱

$handler callable|null

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

return boolean

如果找到並分離處理器

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

            
offsetExists() public method

介面 ArrayAccess 要求此方法。

public boolean offsetExists ( $offset )
$offset integer|string

要檢查的偏移量

                #[\ReturnTypeWillChange]
public function offsetExists($offset)
{
    $this->open();
    return isset($_SESSION[$offset]);
}

            
offsetGet() public method

介面 ArrayAccess 要求此方法。

public mixed offsetGet ( $offset )
$offset integer|string

要檢索元素的偏移量。

return mixed

在偏移量處的元素,如果在偏移量處找不到元素則為 null

                #[\ReturnTypeWillChange]
public function offsetGet($offset)
{
    $this->open();
    return isset($_SESSION[$offset]) ? $_SESSION[$offset] : null;
}

            
offsetSet() public method

介面 ArrayAccess 要求此方法。

public void offsetSet ( $offset, $item )
$offset integer|string

要設定元素的偏移量

$item mixed

元素值

                #[\ReturnTypeWillChange]
public function offsetSet($offset, $item)
{
    $this->open();
    $_SESSION[$offset] = $item;
}

            
offsetUnset() public method

介面 ArrayAccess 要求此方法。

public void offsetUnset ( $offset )
$offset integer|string

要取消設定元素的偏移量

                #[\ReturnTypeWillChange]
public function offsetUnset($offset)
{
    $this->open();
    unset($_SESSION[$offset]);
}

            
on() public method

定義於: 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

事件名稱

$handler callable

事件處理器

$data mixed

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

$append boolean

是否將新的事件處理器附加到現有處理器列表的末尾。如果為 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]);
    }
}

            
open() public method

啟動 session。

public void open ( )

                public function open()
{
    if ($this->getIsActive()) {
        return;
    }
    $this->registerSessionHandler();
    $this->setCookieParamsInternal();
    YII_DEBUG ? session_start() : @session_start();
    if ($this->getUseStrictMode() && $this->_forceRegenerateId) {
        $this->regenerateID();
        $this->_forceRegenerateId = null;
    }
    if ($this->getIsActive()) {
        Yii::info('Session started', __METHOD__);
        $this->updateFlashCounters();
    } else {
        $error = error_get_last();
        $message = isset($error['message']) ? $error['message'] : 'Failed to start session.';
        Yii::error($message, __METHOD__);
    }
}

            
regenerateID() public method

使用新產生的 session ID 更新目前的 session ID。

請參閱 https://php.dev.org.tw/session_regenerate_id 以了解更多詳細資訊。

當 session 不是 active 時,此方法無效。請確保在呼叫此方法之前先呼叫 open()

另請參閱

public void regenerateID ( $deleteOldSession false )
$deleteOldSession boolean

是否刪除舊的相關 session 檔案。

                public function regenerateID($deleteOldSession = false)
{
    if ($this->getIsActive()) {
        // add @ to inhibit possible warning due to race condition
        // https://github.com/yiisoft/yii2/pull/1812
        if (YII_DEBUG && !headers_sent()) {
            session_regenerate_id($deleteOldSession);
        } else {
            @session_regenerate_id($deleteOldSession);
        }
    }
}

            
registerSessionHandler() protected method

註冊 session 處理器。

protected void registerSessionHandler ( )
throws yii\base\InvalidConfigException

                protected function registerSessionHandler()
{
    $sessionModuleName = session_module_name();
    if (static::$_originalSessionModule === null) {
        static::$_originalSessionModule = $sessionModuleName;
    }
    if ($this->handler !== null) {
        if (!is_object($this->handler)) {
            $this->handler = Yii::createObject($this->handler);
        }
        if (!$this->handler instanceof \SessionHandlerInterface) {
            throw new InvalidConfigException('"' . get_class($this) . '::handler" must implement the SessionHandlerInterface.');
        }
        YII_DEBUG ? session_set_save_handler($this->handler, false) : @session_set_save_handler($this->handler, false);
    } elseif ($this->getUseCustomStorage()) {
        if (YII_DEBUG) {
            session_set_save_handler(
                [$this, 'openSession'],
                [$this, 'closeSession'],
                [$this, 'readSession'],
                [$this, 'writeSession'],
                [$this, 'destroySession'],
                [$this, 'gcSession']
            );
        } else {
            @session_set_save_handler(
                [$this, 'openSession'],
                [$this, 'closeSession'],
                [$this, 'readSession'],
                [$this, 'writeSession'],
                [$this, 'destroySession'],
                [$this, 'gcSession']
            );
        }
    } elseif (
        $sessionModuleName !== static::$_originalSessionModule
        && static::$_originalSessionModule !== null
        && static::$_originalSessionModule !== 'user'
    ) {
        session_module_name(static::$_originalSessionModule);
    }
}

            
remove() public method

移除一個 session 變數。

public mixed remove ( $key )
$key string

要移除的 session 變數名稱

return mixed

移除的值,如果沒有此 session 變數則為 null。

                public function remove($key)
{
    $this->open();
    if (isset($_SESSION[$key])) {
        $value = $_SESSION[$key];
        unset($_SESSION[$key]);
        return $value;
    }
    return null;
}

            
removeAll() public method

移除所有 session 變數。

public void removeAll ( )

                public function removeAll()
{
    $this->open();
    foreach (array_keys($_SESSION) as $key) {
        unset($_SESSION[$key]);
    }
}

            
removeAllFlashes() public method

移除所有 Flash 訊息。

請注意,快閃訊息和一般 session 變數共享相同的命名空間。如果您有一個使用相同名稱的一般 session 變數,它將被此方法移除。

另請參閱

public void removeAllFlashes ( )

                public function removeAllFlashes()
{
    $counters = $this->get($this->flashParam, []);
    foreach (array_keys($counters) as $key) {
        unset($_SESSION[$key]);
    }
    unset($_SESSION[$this->flashParam]);
}

            
removeFlash() public method

移除一個 Flash 訊息。

另請參閱

public mixed removeFlash ( $key )
$key string

識別快閃訊息的鍵。請注意,快閃訊息和一般 session 變數共享相同的命名空間。如果您有一個使用相同名稱的一般 session 變數,它將被此方法移除。

return mixed

移除的快閃訊息。如果快閃訊息不存在則為 Null。

                public function removeFlash($key)
{
    $counters = $this->get($this->flashParam, []);
    $value = isset($_SESSION[$key], $counters[$key]) ? $_SESSION[$key] : null;
    unset($counters[$key], $_SESSION[$key]);
    $_SESSION[$this->flashParam] = $counters;
    return $value;
}

            
set() public method

新增一個 session 變數。

如果指定的名稱已存在,則舊值將被覆寫。

public void set ( $key, $value )
$key string

Session 變數名稱

$value mixed

Session 變數值

                public function set($key, $value)
{
    $this->open();
    $_SESSION[$key] = $value;
}

            
setCacheLimiter() public method (自 2.0.14 版本起可用)

設定快取限制器

public void setCacheLimiter ( $cacheLimiter )
$cacheLimiter string

                public function setCacheLimiter($cacheLimiter)
{
    $this->freeze();
    session_cache_limiter($cacheLimiter);
    $this->unfreeze();
}

            
setCookieParams() public method

設定 Session Cookie 參數。

傳遞給此方法的 cookie 參數將與 session_get_cookie_params() 的結果合併。

另請參閱 https://php.dev.org.tw/manual/en/function.session-set-cookie-params.php

public array setCookieParams ( $value )
$value array

Cookie 參數,有效鍵包括:lifetimepathdomainsecurehttponly。從 Yii 2.0.21 開始,也支援 sameSite。它需要 PHP 7.3.0 或更高版本。為了安全起見,如果在使用不受支援的 PHP 版本時設定了 sameSite,將會拋出例外。若要在不同的 PHP 版本中使用此功能,請先檢查版本。例如: `php [

'sameSite' => PHP_VERSION_ID >= 70300 ? yii\web\Cookie::SAME_SITE_LAX : null,

] ` 請參閱 https://owasp.org/www-community/SameSite 以取得關於 sameSite 的更多資訊。

throws yii\base\InvalidArgumentException

如果參數不完整。

                public function setCookieParams(array $value)
{
    $this->_cookieParams = $value;
}

            
setFlash() public method

設定一個 Flash 訊息。

快閃訊息將在請求中被存取後自動刪除,並且刪除將在下一個請求中發生。如果已經存在具有相同鍵的快閃訊息,它將被新的訊息覆寫。

另請參閱

public void setFlash ( $key, $value true, $removeAfterAccess true )
$key string

識別 Flash 訊息的鍵。 請注意,Flash 訊息和一般 session 變數共用相同的命名空間。 如果您有一個使用相同名稱的一般 session 變數,其值將會被此方法覆寫。

$value mixed

快閃訊息

$removeAfterAccess boolean

快閃訊息是否應僅在被存取後自動移除。如果為 false,則快閃訊息將在下一個請求後自動移除,無論是否被存取。如果為 true(預設值),則快閃訊息將保留到被存取之後。

                public function setFlash($key, $value = true, $removeAfterAccess = true)
{
    $counters = $this->get($this->flashParam, []);
    $counters[$key] = $removeAfterAccess ? -1 : 0;
    $_SESSION[$key] = $value;
    $_SESSION[$this->flashParam] = $counters;
}

            
setGCProbability() public method

public void setGCProbability ( $value )
$value float

每次 session 初始化時啟動 GC (垃圾收集) 程序的機率 (百分比)。

throws yii\base\InvalidArgumentException

如果值不在 0 到 100 之間。

                public function setGCProbability($value)
{
    $this->freeze();
    if ($value >= 0 && $value <= 100) {
        // percent * 21474837 / 2147483647 ≈ percent * 0.01
        ini_set('session.gc_probability', floor($value * 21474836.47));
        ini_set('session.gc_divisor', 2147483647);
    } else {
        throw new InvalidArgumentException('GCProbability must be a value between 0 and 100.');
    }
    $this->unfreeze();
}

            
setHasSessionId() public method

設定指出目前請求是否已發送 session ID 的值。

提供此方法是為了讓您可以覆寫確定 session ID 是否已傳送的預設方式。

public void setHasSessionId ( $value )
$value boolean

目前請求是否已發送 session ID。

                public function setHasSessionId($value)
{
    $this->_hasSessionId = $value;
}

            
setId() public method

設定 session ID。

這是 PHP session_id() 的包裝器。

public void setId ( $value )
$value string

目前 session 的 session ID

                public function setId($value)
{
    session_id($value);
}

            
setName() public method

設定目前 session 的名稱。

這是 PHP session_name() 的包裝器。

public void setName ( $value )
$value string

目前 session 的 session 名稱,必須是字母數字字串。預設為 "PHPSESSID"。

                public function setName($value)
{
    $this->freeze();
    session_name($value);
    $this->unfreeze();
}

            
setSavePath() public method

設定目前的 session 儲存路徑。

這是 PHP session_save_path() 的包裝器。

public void setSavePath ( $value )
$value string

目前的 session 儲存路徑。這可以是目錄名稱或 路徑別名

throws yii\base\InvalidArgumentException

如果路徑不是有效的目錄

                public function setSavePath($value)
{
    $path = Yii::getAlias($value);
    if (is_dir($path)) {
        session_save_path($path);
    } else {
        throw new InvalidArgumentException("Session save path is not a valid directory: $value");
    }
}

            
setTimeout() public method

public void setTimeout ( $value )
$value integer

資料將被視為「垃圾」並被清除的秒數

                public function setTimeout($value)
{
    $this->freeze();
    ini_set('session.gc_maxlifetime', $value);
    $this->unfreeze();
}

            
setUseCookies() public method

設定指出是否應使用 Cookie 儲存 session ID 的值。

可能的三種狀態

  • true:將使用 cookies 且僅使用 cookies 來儲存 session ID。
  • false:將不使用 cookies 來儲存 session ID。
  • null:如果可能,將使用 cookies 來儲存 session ID;如果不可能,將使用其他機制 (例如 GET 參數)
public void setUseCookies ( $value )
$value boolean|null

指出是否應使用 Cookie 儲存 session ID 的值。

                public function setUseCookies($value)
{
    $this->freeze();
    if ($value === false) {
        ini_set('session.use_cookies', '0');
        ini_set('session.use_only_cookies', '0');
    } elseif ($value === true) {
        ini_set('session.use_cookies', '1');
        ini_set('session.use_only_cookies', '1');
    } else {
        ini_set('session.use_cookies', '1');
        ini_set('session.use_only_cookies', '0');
    }
    $this->unfreeze();
}

            
setUseStrictMode() public 方法 (自版本 2.0.38 起可用)
public void setUseStrictMode ( $value )
$value boolean

是否啟用嚴格模式。當設定為 true 時,此設定會阻止 session 組件使用未初始化的 session ID。 注意:在 PHP < 5.5.2 上啟用 useStrictMode 僅在使用自訂儲存類別時才受支援。 警告! 儘管啟用嚴格模式對於安全 session 是強制性的,但 'session.use-strict-mode' 的預設值為 0

                public function setUseStrictMode($value)
{
    if (PHP_VERSION_ID < 50502) {
        if ($this->getUseCustomStorage() || !$value) {
            self::$_useStrictModePolyfill = $value;
        } else {
            throw new InvalidConfigException('Enabling `useStrictMode` on PHP < 5.5.2 is only supported with custom storage classes.');
        }
    } else {
        $this->freeze();
        ini_set('session.use_strict_mode', $value ? '1' : '0');
        $this->unfreeze();
    }
}

            
setUseTransparentSessionID() public 方法

public void setUseTransparentSessionID ( $value )
$value boolean

是否啟用透明 sid 支援。

                public function setUseTransparentSessionID($value)
{
    $this->freeze();
    ini_set('session.use_trans_sid', $value ? '1' : '0');
    $this->unfreeze();
}

            
trigger() public 方法

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

觸發一個事件。

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

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

事件名稱

$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);
}

            
unfreeze() protected 方法 (自版本 2.0.14 起可用)

啟動 session 並從暫存變數還原資料

protected void unfreeze ( )

                protected function unfreeze()
{
    if (null !== $this->_frozenSessionData) {
        YII_DEBUG ? session_start() : @session_start();
        if ($this->getIsActive()) {
            Yii::info('Session unfrozen', __METHOD__);
        } else {
            $error = error_get_last();
            $message = isset($error['message']) ? $error['message'] : 'Failed to unfreeze session.';
            Yii::error($message, __METHOD__);
        }
        $_SESSION = $this->_frozenSessionData;
        $this->_frozenSessionData = null;
    }
}

            
updateFlashCounters() protected 方法

更新 Flash 訊息的計數器並移除過期的 Flash 訊息。

此方法應僅在 init() 中調用一次。

protected void updateFlashCounters ( )

                protected function updateFlashCounters()
{
    $counters = $this->get($this->flashParam, []);
    if (is_array($counters)) {
        foreach ($counters as $key => $count) {
            if ($count > 0) {
                unset($counters[$key], $_SESSION[$key]);
            } elseif ($count == 0) {
                $counters[$key]++;
            }
        }
        $_SESSION[$this->flashParam] = $counters;
    } else {
        // fix the unexpected problem that flashParam doesn't return an array
        unset($_SESSION[$this->flashParam]);
    }
}