一、Cookie
①、添加 Cookie
//第一种方法
$cookie = new \yii\web\Cookie();
$cookie -> name = "lulubin"; //cookie的名称
$cookie -> expire = time() + 3600; //存活的时间
$cookie -> httpOnly = true; //无法通过 js 读取 cookie
$cookie -> value = "cookieValue"; //cookie的值
\Yii::$app->response->cookies->add($cookie);
//第二种方法
$cookie = new \yii\web\Cookie([
"name" => "lulubin",
"expire" => time() + 3600,
"httpOnly " => true,
"value" => "cookieValue"
]);
\Yii::$app->response->cookies->add($cookie);
②、读取 Cookie
$cookie = \Yii::$app->request->cookies;
//返回一个yii\web\Cookie对象
$cookie->get("lulubin");
//直接返回 Cookie 的值
$cookie->getValue("lulubin"); //$cookie["lulubin"] 其实这样也是可以读取的
//判断一个Cookie是否存在
$cookie->has("lulubin");
//读取Cookie的总数
$cookie->count();
③、删除 Cookie
$cookie = Yii::$app->request->cookies->get("lulubin");
//移除一个 Cookie 对象
\Yii::$app->response->getCookies()->remove($cookie);
//移除所有 Cookie
\Yii::$app->response->getCookies()->removeAll();
注意:对Cookie进行增删改时调用的response , 对Cookie读取时使用的是Request
二、Session
①、添加 session
$session = \Yii::$app->session;
$session->set("lulubin_name" , "lulubin");
$session->set("lulubin_array" ,[1,2,3]);
②、读取 session
$session = \Yii::$app->session;
//读取一个Session
$session->get("lulubin_name);
③、删除 session
$session = \Yii::$app->session;
//删除一个session
$session->remove("lulubin_name");
//删除所有session
$session->removeAll();