Php $\u COOKIE仅存储上次插入的值
我试图在cookie中插入多个值,但我只能存储一个值。这是我的密码Php $\u COOKIE仅存储上次插入的值,php,arrays,cookies,Php,Arrays,Cookies,我试图在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="&l
<?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>
我正在努力得到这个
setcookie('cookie', serialize($cookie_value), time()+3600);
不能直接将数组存储到cookie中 一种方法是序列化数据:
$data = unserialize($_COOKIE['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));
如前所述,检查cookie中是否已经存在值。如果确实如此,则首先提取该值,然后添加新值
if (preg_match('/^[\w]{3}[\d]{5}$/', $_POST['productid'])) { ... }
您可能需要将此处对is\u numeric
的调用替换为preg\u match
,以检查更具体的产品ID格式。例如:
此外,在与
setcookie()
相同的执行周期内,您将无法在$\u COOKIE
数组中看到任何值。您需要等待浏览器在下一个请求时发送回cookie,然后才能在$\u cookie
数组中看到填充的值。所需的行为是什么?实际输出是什么?在覆盖cookie之前,您没有读取cookie的内容。你能举个例子吗?我知道这会覆盖现有的cookie值。但是如何获得多个值如果要这样做,则存在一些限制/陷阱。1) Cookie的大小有限(官方称为4KB)。2)它们在客户端上可能会被弄乱。因此,1)使用唯一id将数组存储在会话或数据库中。2)在cookie中发送唯一id。我倾向于使用唯一id的散列,但这不是必需的。注意:PHPunserialize()
函数可用于远程代码执行,永远不应用于攻击者定义的字符串。我收到警告消息:array\u merge():参数#1不是数组。这是答案,但OP的产品id似乎不是数字。使用正则表达式为您的特定产品id案例更新答案。
$data = unserialize($_COOKIE['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));
if (preg_match('/^[\w]{3}[\d]{5}$/', $_POST['productid'])) { ... }