php session实现购物车
PHP Session 实现购物车
初始化 Session
确保在使用 Session 前调用 session_start() 函数。通常放在 PHP 文件的最顶部。
<?php
session_start();
?>
添加商品到购物车
通过 $_SESSION 超全局数组存储购物车数据。可以设计为一个关联数组,商品 ID 作为键,数量和详细信息作为值。
// 添加商品到购物车
if (isset($_POST['add_to_cart'])) {
$product_id = $_POST['product_id'];
$product_name = $_POST['product_name'];
$product_price = $_POST['product_price'];
$quantity = $_POST['quantity'];
// 检查购物车是否已存在该商品
if (isset($_SESSION['cart'][$product_id])) {
$_SESSION['cart'][$product_id]['quantity'] += $quantity;
} else {
$_SESSION['cart'][$product_id] = [
'name' => $product_name,
'price' => $product_price,
'quantity' => $quantity
];
}
}
更新购物车商品数量
允许用户修改购物车中商品的数量。

// 更新商品数量
if (isset($_POST['update_cart'])) {
$product_id = $_POST['product_id'];
$quantity = $_POST['quantity'];
if (isset($_SESSION['cart'][$product_id])) {
$_SESSION['cart'][$product_id]['quantity'] = $quantity;
}
}
从购物车中移除商品
通过 unset() 函数删除特定商品。
// 移除商品
if (isset($_POST['remove_from_cart'])) {
$product_id = $_POST['product_id'];
if (isset($_SESSION['cart'][$product_id])) {
unset($_SESSION['cart'][$product_id]);
}
}
清空购物车
直接清空 $_SESSION['cart'] 数组。

// 清空购物车
if (isset($_POST['clear_cart'])) {
unset($_SESSION['cart']);
}
显示购物车内容
遍历 $_SESSION['cart'] 并显示商品信息和总价。
// 显示购物车内容
if (isset($_SESSION['cart']) && !empty($_SESSION['cart'])) {
$total = 0;
foreach ($_SESSION['cart'] as $product_id => $item) {
echo "商品名称: " . $item['name'] . "<br>";
echo "单价: " . $item['price'] . "<br>";
echo "数量: " . $item['quantity'] . "<br>";
$subtotal = $item['price'] * $item['quantity'];
echo "小计: " . $subtotal . "<br><br>";
$total += $subtotal;
}
echo "总价: " . $total;
} else {
echo "购物车为空";
}
注意事项
- 确保在每个使用 Session 的页面顶部调用
session_start()。 - 对用户输入进行验证和过滤,防止安全漏洞。
- 考虑使用数据库持久化购物车数据,以便用户下次登录时恢复购物车。
示例表单
以下是一个简单的表单示例,用于添加商品到购物车。
<form method="post" action="cart.php">
<input type="hidden" name="product_id" value="1">
<input type="hidden" name="product_name" value="示例商品">
<input type="hidden" name="product_price" value="10.99">
<input type="number" name="quantity" value="1" min="1">
<button type="submit" name="add_to_cart">加入购物车</button>
</form>






