【问题标题】:Why is $_COOKIE[$name] returning null when it has a value?为什么 $_COOKIE[$name] 有值时返回 null?
【发布时间】: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


【解决方案1】:

你的代码好像是对的,我已经在线测试了。

enter link description here

【讨论】:

  • 假设您使用两个不同的 id 运行该函数两次。 print_r(json_decode($_COOKIE[$name], true));只显示一个 id 而不是多个 id。
  • 我可能错了,但我认为您的链接发生的情况是 cookie 已关闭,因此它每次都以空数组开头,因此它跳过了我的函数中无法读取的错误部分之前的 cookie 值。
【解决方案2】:

请试试这个代码:

function add_this_id($the_id) {
    $name = "mycookie";
    $value = isset( $_COOKIE[$name] ) ? json_decode($_COOKIE[$name],   true) : array();
    echo "Value From Cookie";
    echo "<pre>";
    print_r($value);
    array_push($value, $the_id); // Changed HERE
    $expire = time() + (60*60*24); //expire in 24 hours

    setcookie($name, json_encode($value), $expire);
    $_COOKIE[$name] = json_encode($value);
    print_r(json_decode($_COOKIE[$name], true));
    die();
}
  add_this_id('123'); //FIRST ATTEMPT
  add_this_id('234'); //SECOND ATTEMPT REMOVE FIRST ATTMEPT LINE

输出:

//First Attempt  
Value From Cookie
Array
(
)
Array
(
   [0] => 123
)

//Second Attempt
Value From Cookie
Array
(
   [0] => 123
)
Array
(
   [0] => 123
   [1] => 234
)

【讨论】:

  • 似乎 array_push 和我的代码做同样的事情,我认为错误的部分是函数中的第二行,当 cookie 存在时,它没有正确读取值,所以它不能附加到cookie 中的值。当我在附加新 ID 之前检查 $value 是否是一个数组时,它并没有说它是一个数组!
  • 我刚刚检查了代码,它工作正常,第一次尝试我在 cookie 中添加了“123”,第二次尝试我添加了“234”,第二次尝试我有在行 print_r(json_decode($_COOKIE[$name], true)); 中有两个值
  • 我认为您是对的,该功能应该可以工作,但正如我所指出的,即使已设置 $_COOKIE 也会被读取为 null。我在 WordPress 中执行此操作,并在我的 function.php 中编写此代码,并通过 AJAX 调用它。我不知道这是否会导致问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-12-28
  • 1970-01-01
  • 1970-01-01
  • 2015-11-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多