设置cookie
$cookies = Yii::$app->response->cookies;
if (! empty ( $uid )) {
$uCookie=$cookies->add(new Cookie([
'name' => 'uid_ck',
'value' =>$uid,
'expire' =>time()+ 30*24*3600,
'domain'=>'.yiwang.com'//作用域写字符串
]));
}
清除cookie
$cookie = Yii::$app->response->cookies;
$cookie->remove('uid_ck');
如果以上方法清除不了你的cookie还可以再加上下边这个
$cookie = Yii::$app->response->cookies;
$uCookie=$cookie->add(new Cookie([
'name' => 'uid_ck',
'value' =>'',
'expire' =>time() - 30*24*3600,
'domain'=>$domainCk
]));
获取cookie
//检查是否存在该值,然后再获取
$cookies = Yii::$app->request->cookies;
if ($cookies->has('uid_ck')) {
$openid = $cookies->get('uid_ck');
}
yii2清除不了cookie值,存不了cookie值
公众号设置的退出登录时不时不管用
yii2清除不了cookie值,存不了cookie值
1)发现同一个方法里因为既有设置cookie的也有获取cookie的地方,心想着上边用了,下边再覆盖这个变量名$cookies就可以了,但是发现不行,
以下是我出错源代码
$cookies = Yii::$app->request->cookies;
$openid = $cookies->get('optKey_open');//可以取到值
$cookies = Yii::$app->response->cookies;//改为$cookie
$cookies->add(new Cookie([//存不了//改为$cookie就可以
'name' => 'isNewUser',
'value' => 1,
'expire' => $setTime + 10,
'domain' => $domainCk
]));
原因:设置存取的cookie变量同名了
2)还有一个是退不出登录
以下是我的出错源代码
$cookie = Yii::$app->response->cookies;
$a= $cookie->add(new Cookie([
'name' => 'uid_ck',
'value' => '',
'expire' => time() - 30 * 24 * 3600,
'domain' => $domainCk
]));
$a=$cookie->add(new Cookie([
'name' => 'optKey_open',
'value' => '',
'expire' => time() - 30 * 24 * 3600,
'domain' => $domainCk
]));
就是因为同名$a,可以去掉"$a=",或者写成两个不同的变量名,同名可能覆盖或者像我这样的两个都设置不成功