【发布时间】:2016-09-08 13:13:04
【问题描述】:
我正在编写一个函数,每次您单击某些带有 data-id 属性的链接时都会调用该函数。我想在数组中添加 id 并将它们设置在 cookie 中,但我无法读取 cookie。到目前为止,这是我所拥有的:
function add_this_id($the_id) {
$name = "mycookie";
/* line below is the issue: */
$value = isset( $_COOKIE[$name] ) ? json_decode($_COOKIE[$name], true) : array();
$value[] = $the_id;
$expire = time() + (60*60*24); //expire in 24 hours
setcookie($name, json_encode($value), $expire, '/');
$_COOKIE[$name] = json_encode($value);
print_r($value);
print_r(json_decode($_COOKIE[$name], true));
die();
}
第一次工作并创建 cookie 时,我可以检查 ID 并将其视为 cookie 的值。但是在第二次尝试时,因为 cookie 已经存在,函数json_decode($_COOKIE[$name], true) 的第 2 行返回 null 而不是数组,因此我无法将新 ID 附加到它。所以我尝试将它包装在一个数组中,如下所示:
$value = isset( $_COOKIE[$name] ) ? array(json_decode($_COOKIE[$name], true)) : array();
但所做的只是返回一个空数组,因此我可以设置当前 ID,现在我陷入了一个循环,我一直从一个空数组开始,并且永远无法附加 ID。为什么设置后我无法读取$_COOKIE[$name]?有任何想法吗?
【问题讨论】:
-
@RyanVincent 我尝试了两种转储,第一个只是重申了我自己的发现,即 cookie 返回为空。我还转储了 id,它表明我正确设置了 id。我不明白为什么当我通过浏览器检查 cookie 时,我确实在其中看到了一个 ID 字符串,但是当我尝试读取它时,它返回为 null。
标签: php arrays wordpress cookies