我知道,多个值可以被设置为使用网站这样: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。
你正在存储一个(JSON)字符串,你为什么期望组件返回一些不同的东西? – ndm
因为在正常情况下,cookie中的json_encoded字符串返回为数组。当我对它进行json_decode时,我得到一个错误。错误是“它已经是数组而不是字符串” – trante
这只有在实际从cookie中读取数据时才会发生。如果没有新的请求,它将读取存储在组件缓冲区中的数据,该数据保持原样。 – ndm