【问题标题】:Add array to array stored in cookie将数组添加到存储在 cookie 中的数组
【发布时间】:2013-12-10 00:41:31
【问题描述】:

将数组变量存储为 cookie 时遇到问题,然后将单独的数组添加到已经包含该数组的 cookie 中

$mysqli = mysqli_connect($db_host,$db_user,$db_pass,$db_base);
        if (mysqli_connect_errno()) 
        {
            printf("Connect failed: %s\n", mysqli_connect_error());
            exit();
        }
        // Displays a message saying product was added to the basket
        $message = $_POST['product_name']." was added to the basket";
        echo "<script>alert(".$message.")</script>";

        // Sets the basket
        $itemID = $_POST['product_id'];
        $itemQuantity = $_POST['product_quantity'];
        if ($itemQuantity > 0)
        {
            $items = [$itemID, $itemQuantity];

            // Returns cookie value as array
            $basket_array = (unserialize($_COOKIE['eg_basket']));

            // Adds to array into cookie array
            $basket = serialize(array_push($basket_array, $items));

            // Sets basket back as cookie
            setcookie('eg_basket', $basket); // will expire on browser close

            // Displays message
            echo "<h3 style='text-align:center'>".$_POST['product_name']." was added to the basket</h3>";
            echo "<br/>";
            echo "<p style='text-align:center'>Please click below to return to the previous page</p>";
        }
        else
        {
            echo "<h3 style='text-align:center'>ERROR: ".$_POST['product_name']." was not added to the basket, invalid quantity given</h3>";
        }

            echo "<form method='POST' action='product_info.php'><input style='display:none' type='number' name='product_id_POST' value='".$_POST['product_id']."'><input style='text-align:center' type='submit' value='Return'></form>";


        // close the connection
        mysqli_close($mysqli);
    ?>

我要做的是创建一个 cookie 来存储产品 ID 数组和数量

例如cookie = [[product_id, 数量],[product_id, 数量],.......]; 然而

我很确定情况并非如此,但这是我用来创建篮子 cookie 的代码(如果它不存在)(这可能是 cookie 不接受任何新值的原因

// Checks is cookie is already set - basket only
    if (!isSet($_COOKIE['eg_basket']))
    {
        $basket = serialize([]);
        setcookie('eg_basket', $basket); // will expire on browser close
    }

谢谢,非常感谢任何帮助

公牛

【问题讨论】:

  • 我建议你把cookie改成session,这样更容易管理也更安全^_^

标签: php html arrays cookies


【解决方案1】:

当标头已发送时,您无法向浏览器发送 cookie,请参阅the manual

因此,您需要记录您的消息而不在此处回显任何内容:

echo "<script>alert(".$message.")</script>";

并确保在您的 setcookie() 行之前没有其他输出发送到浏览器。

【讨论】:

    猜你喜欢
    • 2014-04-23
    • 1970-01-01
    • 1970-01-01
    • 2012-07-08
    • 2011-11-16
    • 2011-06-10
    • 1970-01-01
    • 1970-01-01
    • 2018-11-28
    相关资源
    最近更新 更多