php session实现购物车
使用 PHP Session 实现购物车功能
初始化 Session 和购物车
在 PHP 脚本的开头调用 session_start() 以启用 Session 功能。检查 Session 中是否已存在购物车数组,若不存在则初始化一个空数组。
session_start();
if (!isset($_SESSION['cart'])) {
$_SESSION['cart'] = array();
}
添加商品到购物车
通过表单或 URL 参数接收商品信息(如 ID、名称、价格、数量),并将其添加到 Session 中的购物车数组。为避免重复添加同一商品,可先检查商品是否已存在。
$product_id = $_POST['product_id'];
$product_name = $_POST['product_name'];
$price = $_POST['price'];
$quantity = $_POST['quantity'];
// 检查商品是否已存在
if (isset($_SESSION['cart'][$product_id])) {
$_SESSION['cart'][$product_id]['quantity'] += $quantity;
} else {
$_SESSION['cart'][$product_id] = array(
'name' => $product_name,
'price' => $price,
'quantity' => $quantity
);
}
显示购物车内容
遍历 Session 中的购物车数组,计算总价并展示商品列表。
if (!empty($_SESSION['cart'])) {
$total = 0;
foreach ($_SESSION['cart'] as $id => $item) {
echo "商品: {$item['name']}, 单价: {$item['price']}, 数量: {$item['quantity']}<br>";
$total += $item['price'] * $item['quantity'];
}
echo "总价: $total";
} else {
echo "购物车为空";
}
更新购物车商品数量
通过表单提交修改后的商品数量,更新 Session 中对应商品的数据。
$product_id = $_POST['product_id'];
$new_quantity = $_POST['quantity'];
if (isset($_SESSION['cart'][$product_id])) {
$_SESSION['cart'][$product_id]['quantity'] = $new_quantity;
}
删除购物车中的商品
根据商品 ID 从 Session 购物车数组中移除指定商品。
$product_id = $_GET['product_id'];
if (isset($_SESSION['cart'][$product_id])) {
unset($_SESSION['cart'][$product_id]);
}
清空购物车
直接重置 Session 中的购物车数组为空。
$_SESSION['cart'] = array();
注意事项
- 确保在所有操作购物车的页面顶部调用
session_start()。 - 对用户输入的数据进行验证和过滤,防止安全漏洞(如 XSS 或 SQL 注入)。
- 考虑为购物车添加超时机制,长时间未操作时自动清空。







