yii2 Cookie
讀取 Cookies
$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
// 從"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驗證
return [
'components' => [
'request' => [
'cookieValidationKey' => 'fill in a secret key here',
],
],
];