1、Cookie
Yii2的Cookie主要是通过yii\web\Request
和yii\web\Response
进行操作的 ,通过\Yii::$app->response->getCookies()->add()
添加Cookie,通过\Yii::$app->request->cookies
读取Cookie.
1)添加一个Cookie
<?php//第一种方法$cookie = new \yii\web\Cookie();$cookie -> name = 'smister'; //cookie的名称$cookie -> expire = time() + 3600; //存活的时间$cookie -> httpOnly = true; //无法通过js读取cookie$cookie -> value = 'cookieValue'; //cookie的值\Yii::$app->response->getCookies()->add($cookie);//第二种方法$cookie = new \yii\web\Cookie([ ‘name’ => ‘smister’, ‘expire’ => time() + 3600, ‘httpOnly ’ => true, ‘value’ => ‘cookieValue’ ]); \Yii::$app->response->getCookies()->add($cookie);?>
2) 读取一个Cookie
<?php$cookie = \Yii::$app->request->cookies;//返回一个\yii\web\Cookie对象$cookie->get(‘smister’);//直接返回Cookie的值$cookie->getValue(‘smister’); //$cookie[‘smister’] 其实这样也是可以读取的//判断一个Cookie是否存在$cookie->has(‘smister’);//读取Cookie的总数$cookie->count();//$cookie->getCount();跟count一样?>
3) 删除Cookie
<?php$cookie = Yii::$app->request->cookies->get(‘smister’);//移除一个Cookie对象\Yii::$app->response->getCookies()->remove($cookie);//移除所有Cookie,目前好像不太好使\Yii::$app->response->getCookies()->removeAll();?>
4) 注意
对Cookie进行增删改时调用的response , 对Cookie读取时使用的是Request
2、Session
Yii2的Session比较简单 ,直接通过\Yii::$app->session进行操作就好了
1) 添加一个session
<?php$session = \Yii::$app->session;$session->set('smister_name' , 'myname');$session->set('smister_array' ,[1,2,3]);?>
2) 读取一个session
<?php$session = \Yii::$app->session;//读取一个Session$session->get('smister_name); ?>
3) 删除Session
<?php$session = \Yii::$app->session;//删除一个session$session->remove(‘smister_name’);//删除所有session$session->removeAll();?>