2013-11-01 20 views
1

我知道,多个值可以被设置为使用网站这样:CakePHP中设置多个值到一个饼干

If you want to write more than one value to the cookie at a time, 
    you can pass an array: 

$this->Cookie->write('User', 
    array('name' => 'Larry', 'role' => 'Lead') 
); 

由于一些设计问题,我需要在我的控制器动作的不同部位设置cookie的值。但似乎这样的minimalized码不起作用:

public function myfunction() { 
    $text = ""; 
    // to be sure that this cookie doesn't exist 
    $this->Cookie->delete('mycookie'); 
    // getting data from cookie, result is NULL 
    $data = $this->Cookie->read('mycookie'); 
    $text .= "data 1 type: ".gettype($data)."<br>"; 
    $key="mike"; 
    $value=12; 
    // adding key-value to cookie 
    $data[$key] = $value; 
    // serializing and writing cookie 
    $dataS = json_encode($data); 
    $this->Cookie->write('mycookie', $dataS, FALSE, '10 days'); 

    // reading cookie again, but this time result is 
    // string {"mike":12} not an array 
    $data = $this->Cookie->read('mycookie'); 
    $text .= "data 2 type: ".gettype($data)."<br>"; 
    $key="john"; 
    $value=20; 
    // Illegal string offset error for the line below 
    $data[$key] = $value; 
    $dataS = json_encode($data); 
    $this->Cookie->write('mycookie', $dataS, FALSE, '10 days'); 

    echo $text; 

} 

页输出:

Warning (2): Illegal string offset 'john' [APP/Controller/MyController.php, line 2320] 
data 1 type: NULL 
data 2 type: string 

从上面的代码中, “迈克12” 设置为成功的cookie。但是当我第二次读取cookie数据时,我得到这样一个字符串:{"mike":12}。不是数组。

当我为“数据2”制作gettype时,输出为“字符串”。因为$data是字符串不是数组。

那么不可能在一个动作中一个一个地设置同一个cookie吗?

编辑: 当我创建一个数据数组,json_encode该数组并将其内容写入cookie。然后,在另一个控制器中,当我读取该cookie内容并将它分配给一个变量时,它会自动转换为Array。

+0

你正在存储一个(JSON)字符串,你为什么期望组件返回一些不同的东西? – ndm

+0

因为在正常情况下,cookie中的json_encoded字符串返回为数组。当我对它进行json_decode时,我得到一个错误。错误是“它已经是数组而不是字符串” – trante

+1

这只有在实际从cookie中读取数据时才会发生。如果没有新的请求,它将读取存储在组件缓冲区中的数据,该数据保持原样。 – ndm

回答

1

以JSON格式对数据进行编码和解码是Coookie组件的内部功能,您的应用程序不应该依赖它!实现可能会改变,你的代码将被破坏。

当前仅当数据实际从cookie中读取时需要新的请求才会解码JSON数据。在同一请求中,您将访问组件缓冲的原始数据。

所以不是这个JSON啄你应该遵守的规则,并传递一个数组:

$data = array(); 

$key = 'mike'; 
$value = 12; 

$data[$key] = $value; 

$this->Cookie->write('mycookie', $data); 

// ... do some stuff, and then somewhere else: 

$data = $this->Cookie->read('mycookie'); 

$key = 'john'; 
$value = 20; 

$data[$key] = $value; 
$this->Cookie->write('mycookie', $data); 

或使用点符号(这将导致多个Cookie):

$key = 'mike'; 
$value = 12; 
$this->Cookie->write('mycookie.' . $key, $value); 

// ... do some stuff, and then somewhere else: 

$key = 'john'; 
$value = 20; 
$this->Cookie->write('mycookie.' . $key, $value); 

参见http://book.cakephp.org/2.0/en/core-libraries/components/cookie.html#using-the-component

+0

谢谢你的回答。我明白我的错误..但是你提到Cake的内部功能可以改变。那么我应该怎样做以保证未来版本的安全?在编写cookie之前,我编码数组。当我读取cookie时,我只使用CookieComponent的读取函数,而不对其进行json_decode。因为结果来自一个数组。我应该再次json_decode输出吗?谢谢。 – trante

+0

如示例中所示,根本不编码为JSON,而是传递原始数组,该组件将负责处理它。或者,在适当的情况下,使用点符号样式。这两种方法都可以安全使用,并且可以预期在主要版本更改之前不会中断(如2.x到3.x)。 – ndm

+0

嗯,我编码的数据,因为有时我添加重要的字符串cookie,他们可以包含“;”字符。 – trante