【发布时间】:2013-11-13 05:45:17
【问题描述】:
我知道可以通过这种方式为 cookie 设置多个值:
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 值。但似乎这个最小化的代码不起作用:
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
从上面的代码中,“Mike 12”成功设置为cookie。但是当我第二次读取 cookie 数据时,我得到一个像这样的字符串:{"mike":12}。不是数组。
当我为“数据 2”创建gettype 时,输出为“字符串”。
所以当我创建$data["john"]=20 时,我得到Illegal string offset error 因为$data 是字符串而不是数组。
那么是不是不能在一个动作中一个一个地设置相同的cookie?
编辑: 当我创建一个数据数组时,json_encode 该数组并将其内容写入 cookie。然后在另一个控制器中,当我读取该 cookie 内容并将其分配给一个变量时,它会自动转换为数组。
【问题讨论】:
-
您正在存储一个 (JSON) 字符串,为什么您希望组件返回不同的内容?
-
因为在正常情况下,cookies 中的 json_encoded 字符串会以数组形式返回。 json_decode 时出现错误。错误是“它已经是数组而不是字符串”
-
只有在实际从 cookie 中读取数据时才会发生这种情况。如果没有新请求,它将读取存储在组件缓冲区中的数据,该缓冲区按原样保存数据。
-
我不知道存在组件缓冲区。我没有在我阅读的文件中遇到..