yii中的cookie的发送和读取

cookies:

  //新创建的cookie会从本地传到服务器上,然后从服务器获取。

(1) cookie的发送

  $cookies = Yii::$app->response->cookies;

   // 在要发送的响应中添加一个新的cookie

  eg:往cookies中添加用户名和密码

  $cookies->add(new Cookie(['name'=>'username', 'value'=>$username,]));

  $cookies->add(new Cookie(['name'=>'password', 'value'=>$password,]));

 

  //删除一个cookie

  $cookies->remove('username');

  //相当于

  unset($cookies['username']);

(2)cookie的获取

  $cookies = Yii::$app->request->cookies;

  // 获取名为 "username" cookie 的值,如果不存在,返回默认值"en"

  $username = $cookies->getValue('username', 'en');

  // 另一种方式获取名为 "username" cookie 的值
  if (($cookie = $cookies->getValue('username')) !== null) {
    $username = $cookie->value;
  }

// 判断是否存在名为username的cookie
if (isset($cookies['username'])) {
    $username= $cookies['username']->value;
  ... }
if($cookies->has('username')){}
 注意:
  $cookies = Yii::$app->response->cookies; //获取不到对应的cookie
  $cookies = Yii::$app->request->cookies; //能获取到对应的cookie,但是只读的
-> 要删除cookies里面的某一个cookie时,先必须要在request中判断是否存在某个cookie,然后在response中删除
     $cookies = Yii::$app->request->cookies;
        if ($cookies->has('user')) {
            Yii::$app->response->cookies->remove('user');
            return $this->redirect('/user/login');
        }
        //如果cookie过期了,当点击logout时,系统跳到登陆界面
        return $this->redirect('/user/login');

 

 

  

  

posted @ 2016-07-26 22:34  艾若菲  阅读(912)  评论(0编辑  收藏  举报