gpt4 book ai didi

php - 在 Cookie 中设置购物车 session

转载 作者:可可西里 更新时间:2023-11-01 01:01:54 24 4
gpt4 key购买 nike

我正在创建一个购物车,我只是使用 session 来更新购物车。但我想将它设置为 cookie 并检索它以供进一步使用......我的购物车 session 是:

$_SESSION['cart'][$pid] = array("item_id" => $pid, "quantity" => $tobesend, "price" => $price_per_q);

我想把这一切都设置到 cookie 中。请帮助。我想知道如果我在这里使用网络存储而不是 cookie 有什么好处......

谢谢你..

最佳答案

Cookies任何使用用户浏览器的人都可以访问,最好的办法是将购物车 session 存储在数据库中,并且只将该数据库条目的行 ID 存储在 cookie 中。所以基本上:

// Store the data in the database, in whatever form you choose
$id = last_insert_id(); // Get the ID of the row in which this information is stored

// Store the id in a cookie
setcookie("cart_session_data_id", $id, time() + 3600 * 24); /* expire in 1 day */

现在您可以在需要时将数据库中的数据检索回 session

// Get the row id from the cookie
$id = $_COOKIE['cart_session_data_id'];

// Use this ID and retrieve the data from the database

为什么选择网络存储而不是 cookie?

  1. 将敏感数据存储在 cookie 中是不明智的,因为 XSS 攻击可以获取所有 cookie
  2. Cookie 给您每个域 4096 字节的限制

更多资源:

  1. http://davidwalsh.name/php-cookies
  2. http://in3.php.net/setcookie
  3. Local Storage vs Cookies
  4. Keep $_SESSION alive with autorenewing counter

关于php - 在 Cookie 中设置购物车 session ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22253512/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com