yii2-Cookie

胡勇健發表於2024-03-30

yii2 Cookie

讀取 Cookies

yii2-Cookie
$cookies = Yii::$app->request->cookies;

// 獲取名為 "language" cookie 的值,如果不存在,返回預設值"en"
$language = $cookies->getValue('language', 'en');

// 另一種方式獲取名為 "language" cookie 的值
if (($cookie = $cookies->get('language')) !== null) {
    $language = $cookie->value;
}

// 可將 $cookies當作陣列使用
if (isset($cookies['language'])) {
    $language = $cookies['language']->value;
}

// 判斷是否存在名為"language" 的 cookie
if ($cookies->has('language')) ...
if (isset($cookies['language'])) ...

傳送Cookies

yii2-Cookie
// 從"response"元件中獲取cookie 集合(yii\web\CookieCollection)
$cookies = Yii::$app->response->cookies;

// 在要傳送的響應中新增一個新的cookie
$cookies->add(new \yii\web\Cookie([
    'name' => 'language',
    'value' => 'zh-CN',
]));

// 刪除一個cookie
$cookies->remove('language');
// 等同於以下刪除程式碼
unset($cookies['language']);

配置 Cookie驗證

yii2-Cookie
return [
    'components' => [
        'request' => [
            'cookieValidationKey' => 'fill in a secret key here',
        ],
    ],
];