php用session实现购物车
使用 PHP Session 实现购物车
初始化 Session
确保在脚本的最开始调用 session_start(),以便使用 Session 功能。通常放在 PHP 文件的开头。
<?php
session_start();
?>
创建购物车结构
购物车可以设计为一个关联数组,存储商品 ID、名称、数量、价格等信息。Session 中的购物车变量通常命名为 $_SESSION['cart']。
if (!isset($_SESSION['cart'])) {
$_SESSION['cart'] = [];
}
添加商品到购物车
通过表单或 AJAX 提交商品信息,将其添加到购物车数组中。检查商品是否已存在,若存在则更新数量,否则新增条目。

$productId = $_POST['product_id'];
$productName = $_POST['product_name'];
$productPrice = $_POST['product_price'];
$quantity = $_POST['quantity'];
if (isset($_SESSION['cart'][$productId])) {
$_SESSION['cart'][$productId]['quantity'] += $quantity;
} else {
$_SESSION['cart'][$productId] = [
'name' => $productName,
'price' => $productPrice,
'quantity' => $quantity
];
}
更新购物车中的商品数量
通过表单提交更新特定商品的数量。若数量为 0 或负数,则移除该商品。
$productId = $_POST['product_id'];
$newQuantity = $_POST['quantity'];
if ($newQuantity > 0) {
$_SESSION['cart'][$productId]['quantity'] = $newQuantity;
} else {
unset($_SESSION['cart'][$productId]);
}
移除购物车中的商品
通过商品 ID 直接从购物车数组中移除对应条目。

$productId = $_POST['product_id'];
unset($_SESSION['cart'][$productId]);
清空购物车
直接清空整个购物车数组。
$_SESSION['cart'] = [];
显示购物车内容
遍历购物车数组,显示商品信息和总价。
if (!empty($_SESSION['cart'])) {
$total = 0;
foreach ($_SESSION['cart'] as $id => $item) {
$subtotal = $item['price'] * $item['quantity'];
$total += $subtotal;
echo "商品: {$item['name']}, 单价: {$item['price']}, 数量: {$item['quantity']}, 小计: $subtotal<br>";
}
echo "总价: $total";
} else {
echo "购物车为空";
}
注意事项
- 确保
session_start()在输出内容之前调用,否则会引发错误。 - 对用户输入进行验证和过滤,避免安全问题。
- 购物车数据仅在 Session 有效期内存在,用户关闭浏览器后可能丢失(取决于 Session 配置)。
通过以上方法,可以实现一个基础的购物车功能。根据需求可以进一步扩展,如添加商品图片、折扣计算等功能。






