首页 > 解决方案 > Cakephp 2多维cookie数组不起作用

问题描述

我无法读取使用 cakephp cookie 组件创建的 cookie。实际上 cookie 正在创建,当我在 write 方法后立即调试时,它会显示整个 cookie。但是,如果我刷新同一页面(操作)cookie 不会读取。在其他控制器操作上,cookie 也没有读取。

var $components = array('Encryption','General','Cookie');

public function beforeFilter()
{
    parent::beforeFilter();
    $this->Auth->allow();   

    $this->Cookie->name =null;
    $this->Cookie->time =2592000;  // or '30 days'
    $this->Cookie->path = '/';
    $this->Cookie->domain =  $_SERVER['HTTP_HOST'];
    //$this->Cookie->secure = true;  // i.e. only sent if using secure HTTPS
    $this->Cookie->key = md5(uniqid(rand(), true));
    //$this->Cookie->httpOnly = true;
    $this->Cookie->type('aes');
}
public function index(){    
    $browserInfo=$this->General->getBrowser();
    $browserName=$browserInfo['name'];
    $cookie_value=md5(uniqid(rand(), true))."_".$browserName;

    $knowTheBae= $this->Cookie->read('know_the_bae'); // this is returning null when i' refresh the page again. 

    if(count($knowTheBae)==0){  
        $this->Cookie->write('know_the_bae.identity',$cookie_value); //this line suppose to execute only first time. But it's executing every time i load this page .
        debug($this->Cookie->read('know_the_bae')); //line no 43
    }
    if($this->Cookie->read('know_the_bae.identity')!=""){
        if($this->Session->read('Auth.User.id')){
            $this->Cookie->write('know_the_bae.user.name',$this->Session->read('Auth.User.username'));
            $this->Cookie->write('know_the_bae.user.id',$this->Session->read('Auth.User.id'));
        }else{
            $this->Cookie->write('know_the_bae.user.name','UNKN_USR');
            $this->Cookie->write('know_the_bae.user', array('name' => 'UNKN_USR', 'role' => 'guest'));

        }
    }else{
        $this->Cookie->write('know_the_bae.identity',$cookie_value);
    }
    $this->Cookie->write("know_the_bae.test",'something going wrong');

    debug($this->Cookie->read('know_the_bae')); //line no 59
}

输出 浏览器cookie

标签: cakephpcookiesmultidimensional-array

解决方案


您正在使用随机密钥来加密和解密您的 cookie:

$this->Cookie->key = md5(uniqid(rand(), true));

这在下一页加载时会有所不同,因此它将无法解密您设置的内容。您必须始终使用相同的密钥,我建议您将其存储在安全的配置文件或环境变量中。


推荐阅读