【问题标题】:$_COOKIE is storing only last inserted value$_COOKIE 仅存储最后插入的值
【发布时间】:2016-03-19 00:21:30
【问题描述】:

我试图在 cookie 中插入多个值,但我只能存储一个值。听到是我的代码。

<?php
session_start();
$rand= "SED".rand(10000,99999);
?>
<!doctype>
<html lang="en">
<body>

<form action="result4.php" method="post">
<input type="hidden" name="productid" value="<?=$rand?>">
<button type="submit">submit</button>
</form>
</body>
</html>

和我的 result4.php

<?php
$cookie_name = "lastview";
$cookie_value = array($_POST['productid']);
$init = json_encode($cookie_value);
setcookie($cookie_name, $init, time() + (86400 * 30));
?>
<?php
echo count($_COOKIE["lastview"]);
echo '<pre>';
print_r($_COOKIE["lastview"]);
echo '</pre>';
?>

输出

1
["SED73204"]

我正在努力解决这个问题

5
["SED73204"]
["SED73507"]
["SED23207"]
["SED73286"]
["SED23294"]

【问题讨论】:

  • 期望的行为是什么?实际输出是多少?
  • 在覆盖之前您没有读取 cookie 的内容。读取它,返回一个数组,添加一个值,再写回去。
  • 怎么读能不能举个例子
  • 我知道它覆盖了现有的 cookie 值。但是如何获取多个值
  • 如果你要这样做,那么有一些限制/陷阱。 1) COOKIES 的大小有限(官方为 4KB) 2) 它们可以在客户端上被弄乱。因此,1) 将数组存储在具有唯一 ID 的会话或数据库中。 2)发送cookie中的唯一ID。我倾向于使用唯一 ID 的哈希值,但这不是必需的。

标签: php arrays cookies


【解决方案1】:

您不能将数组直接存储到 cookie 中,

一种方法是序列化数据:

setcookie('cookie', serialize($cookie_value), time()+3600);

然后反序列化数据:

$data = unserialize($_COOKIE['cookie']);

【讨论】:

  • 注意:PHP unserialize() 函数可用于远程代码执行,绝不应用于攻击者定义的字符串。
【解决方案2】:

如前所述,检查 cookie 中是否已经存在值。如果确实如此,则先提取该值,然后添加新值。

$cookie_name = "lastview";

// Set the cookie value from previous (if exists) or else an empty array
$cookie_value = (isset($_COOKIE[$cookie_name])) ?     
json_decode($_COOKIE[$cookie_name]) : array();

// Add the new value to the array if one exists
if (isset($_POST['productid']) && is_numeric($_POST['productid'])) {
    $cookie_value[] = $_POST['productid'];
}

// Set the cookie
setcookie($cookie_name, json_encode($cookie_value), time() + (86400 * 30));

您可能希望将此处对is_numeric 的调用替换为preg_match,以检查更具体的产品ID 格式。例如:

if (preg_match('/^[\w]{3}[\d]{5}$/', $_POST['productid'])) { ... }

此外,您将无法在与setcookie() 相同的执行周期中看到$_COOKIE 数组中的任何值。您需要等待浏览器在下一个请求中将 cookie 发回,然后才能在 $_COOKIE 数组中看到填充的值。

【讨论】:

  • 我收到警告消息:array_merge(): Argument #1 is not an array in
  • 这是答案,除了 OP 的产品 ID 似乎不是数字
  • 针对您的特定产品 ID 使用正则表达式更新了答案。
猜你喜欢
  • 2020-06-16
  • 2019-10-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-11
  • 2016-03-28
相关资源
最近更新 更多