1、Cookie
Yii2的Cookie主要是通过yii\web\Request
和yii\web\Response
进行操作的 ,通过\Yii::$app->response->getCookies()->add()
添加Cookie,通过\Yii::$app->request->cookies
读取Cookie.
1)添加一个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
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
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
session;$session->set('smister_name' , 'myname');$session->set('smister_array' ,[1,2,3]);?>
2) 读取一个session
session;//读取一个Session$session->get('smister_name);?>
3) 删除Session
session;//删除一个session$session->remove(‘smister_name’);//删除所有session$session->removeAll();?>
PHP/Yii2操作Cookie,常见问题以及注意事项
设置Cookie
PHP
setcookie("name", "Larry", time()+3600);
Yii2
$cookies = Yii::$app->response->cookies; $cookies->add(new \yii\web\Cookie([ 'name' => 'name', 'value' => 'Larry', 'expire'=>time()+3600]));
创建名为"name"的cookie,赋值为"Larry",并且规定该cookie一小时后失效
expire这是一个UNIX时间戳,如果设置为0,或省略,该Cookie将在浏览器关闭时消失
获取Cookie
PHP
$name=$_COOKIE["user"]
Yii2
$cookies = Yii::$app->request->cookies;//注意此处是request$language = $cookies->get('user', 'defaultName');//设置默认值
检查Cookie
PHP
if(isset($_COOKIE["user"])){ }
Yii2
$cookies = Yii::$app->request->cookies; if (isset($cookies['user'])){ }if ($cookies->has('user')){ }if (isset($cookies['user'])){ }
删除Cookie
PHP
setcookie("user", "", time()-3600);//把失效日期设置为过去1小时unset($_COOKIE['user']);###Yii2$cookies = Yii::$app->request->cookies; $cookies->remove('user');
常见问题
A.Cookie的key不能含“.” 符号,会被解析成“_”,导致具有以上符号的key获取不到Cookie的bug
B.区分Yii2中 Yii::$app->request->cookies
和 Yii::$app->response->cookies
不仔细容易直接复制粘贴了。
1.如果把第一个用来设置Cookie,会报错:`The cookie collection is read only`2.如果把第二个用来获取Cookie,程序正常执行未发生异常,但会获取不到Cookie,不容易察觉。。。
C.Cookie的key区分大小写
Yii::$app->request->cookies 和 Yii::$app->response->cookies在yii里面是分开的,前者是客户端(浏览器cookie),后者是服务器端。
所以: Yii::$app->request->cookies主要负责读取 Yii::$app->response->cookies主要负责创建当然两者可以混用,但是根据业务需要,
取客户端cookie之前,在响应中应该写入或修改 如果两者分不清或者使用错误,那就是程序不OOP 思想不到位Detect languageAfrikaansAlbanianArabicArmenianAzerbaijaniBasqueBelarusianBengaliBosnianBulgarianCatalanCebuanoChichewaChinese (Simplified)Chinese (Traditional)CroatianCzechDanishDutchEnglishEsperantoEstonianFilipinoFinnishFrenchGalicianGeorgianGermanGreekGujaratiHaitian CreoleHausaHebrewHindiHmongHungarianIcelandicIgboIndonesianIrishItalianJapaneseJavaneseKannadaKazakhKhmerKoreanLaoLatinLatvianLithuanianMacedonianMalagasyMalayMalayalamMalteseMaoriMarathiMongolianMyanmar (Burmese)NepaliNorwegianPersianPolishPortuguesePunjabiRomanianRussianSerbianSesothoSinhalaSlovakSlovenianSomaliSpanishSundaneseSwahiliSwedishTajikTamilTeluguThaiTurkishUkrainianUrduUzbekVietnameseWelshYiddishYorubaZulu | | AfrikaansAlbanianArabicArmenianAzerbaijaniBasqueBelarusianBengaliBosnianBulgarianCatalanCebuanoChichewaChinese (Simplified)Chinese (Traditional)CroatianCzechDanishDutchEnglishEsperantoEstonianFilipinoFinnishFrenchGalicianGeorgianGermanGreekGujaratiHaitian CreoleHausaHebrewHindiHmongHungarianIcelandicIgboIndonesianIrishItalianJapaneseJavaneseKannadaKazakhKhmerKoreanLaoLatinLatvianLithuanianMacedonianMalagasyMalayMalayalamMalteseMaoriMarathiMongolianMyanmar (Burmese)NepaliNorwegianPersianPolishPortuguesePunjabiRomanianRussianSerbianSesothoSinhalaSlovakSlovenianSomaliSpanishSundaneseSwahiliSwedishTajikTamilTeluguThaiTurkishUkrainianUrduUzbekVietnameseWelshYiddishYorubaZulu | | | | | |
| Options : History : Feedback : | Close |