1. Cookie
Yii2 Cookies are mainly operated through yii/web/Request and yii/web/Response, through /Yii::$app->response->getCookies() ->add() adds Cookie and reads Cookie through /Yii::$app->request->cookies.
1) Add a 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) Read a Cookie
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) Delete Cookie
request->cookies->get(‘smister'); //移除一个Cookie对象 /Yii::$app->response->getCookies()->remove($cookie); //移除所有Cookie,目前好像不太好使 /Yii::$app->response->getCookies()->removeAll(); ?>
4) Note
Perform Cookie The response is called when adding, deleting or modifying. When reading cookies, Request
##2 and Session are used. Yii2's Session is relatively simple and can be performed directly through /Yii::$app->session. Just do it 1) Add a sessionsession; $session->set('smister_name' , 'myname'); $session->set('smister_array' ,[1,2,3]); ?>
session; //读取一个Session $session->get('smister_name); ?>
session; //删除一个session $session->remove(‘smister_name'); //删除所有session $session->removeAll(); ?>