php 购物车实现session
PHP 购物车使用 Session 实现的方法
在 PHP 中,可以使用 $_SESSION 超全局变量来实现购物车功能。Session 是一种服务器端存储机制,适合存储用户购物车数据。
初始化 Session
在脚本开始处调用 session_start() 函数初始化 Session:
session_start();
添加商品到购物车
创建一个数组来存储购物车商品,并将其存入 Session:
if(isset($_POST['add_to_cart'])) {
$product_id = $_POST['product_id'];
$product_name = $_POST['product_name'];
$price = $_POST['price'];
$quantity = $_POST['quantity'];
$cart_item = array(
'id' => $product_id,
'name' => $product_name,
'price' => $price,
'quantity' => $quantity
);
if(!isset($_SESSION['cart'])) {
$_SESSION['cart'] = array();
}
// 检查商品是否已存在
$item_exists = false;
foreach($_SESSION['cart'] as &$item) {
if($item['id'] == $product_id) {
$item['quantity'] += $quantity;
$item_exists = true;
break;
}
}
if(!$item_exists) {
array_push($_SESSION['cart'], $cart_item);
}
}
显示购物车内容
遍历 Session 中的购物车数组显示商品:

if(isset($_SESSION['cart']) && count($_SESSION['cart']) > 0) {
foreach($_SESSION['cart'] as $item) {
echo "ID: ".$item['id']."<br>";
echo "Name: ".$item['name']."<br>";
echo "Price: ".$item['price']."<br>";
echo "Quantity: ".$item['quantity']."<br>";
echo "Total: ".($item['price'] * $item['quantity'])."<br><br>";
}
} else {
echo "Your cart is empty";
}
更新购物车商品数量
提供表单让用户更新商品数量:
if(isset($_POST['update_cart'])) {
foreach($_POST['quantity'] as $id => $quantity) {
foreach($_SESSION['cart'] as &$item) {
if($item['id'] == $id) {
$item['quantity'] = $quantity;
break;
}
}
}
}
从购物车移除商品
实现删除购物车中指定商品的功能:

if(isset($_GET['remove_item'])) {
$id_to_remove = $_GET['remove_item'];
foreach($_SESSION['cart'] as $key => $item) {
if($item['id'] == $id_to_remove) {
unset($_SESSION['cart'][$key]);
break;
}
}
// 重新索引数组
$_SESSION['cart'] = array_values($_SESSION['cart']);
}
清空购物车
提供清空整个购物车的功能:
if(isset($_GET['empty_cart'])) {
unset($_SESSION['cart']);
}
计算购物车总价
计算购物车中所有商品的总价格:
$total = 0;
if(isset($_SESSION['cart'])) {
foreach($_SESSION['cart'] as $item) {
$total += $item['price'] * $item['quantity'];
}
}
echo "Cart Total: $".number_format($total, 2);
安全注意事项
使用 Session 存储购物车数据时需要注意:
- 在操作 Session 前始终调用
session_start() - 对用户输入进行验证和过滤
- 考虑使用 CSRF 令牌保护表单
- 对于敏感操作(如删除)使用 POST 而非 GET 请求
这种实现方式简单直接,适合小型电商网站。对于大型应用,可能需要考虑数据库存储购物车数据以获得更好的持久性和可扩展性。






