用session实现购物车 php
使用 PHP Session 实现购物车功能
初始化 Session 和购物车结构
确保在脚本顶部调用 session_start() 函数以启用 Session 功能。购物车数据结构通常使用关联数组存储商品信息。
<?php
session_start();
if (!isset($_SESSION['cart'])) {
$_SESSION['cart'] = [];
}
?>
添加商品到购物车
通过商品 ID 作为键值,存储商品数量和详细信息。支持重复添加时数量累加。
function addToCart($productId, $quantity, $productDetails) {
if (isset($_SESSION['cart'][$productId])) {
$_SESSION['cart'][$productId]['quantity'] += $quantity;
} else {
$_SESSION['cart'][$productId] = [
'quantity' => $quantity,
'details' => $productDetails
];
}
}
// 示例调用
addToCart(101, 2, ['name' => 'T-Shirt', 'price' => 19.99]);
从购物车移除商品
通过 unset() 函数直接删除指定商品 ID 的数组元素。
function removeFromCart($productId) {
if (isset($_SESSION['cart'][$productId])) {
unset($_SESSION['cart'][$productId]);
}
}
更新商品数量
直接修改指定商品 ID 的数量值,可增加验证防止非数字输入。
function updateQuantity($productId, $newQuantity) {
if (isset($_SESSION['cart'][$productId]) && $newQuantity > 0) {
$_SESSION['cart'][$productId]['quantity'] = $newQuantity;
}
}
计算购物车总价
遍历购物车数组,累加每个商品的单价乘以数量。
function calculateTotal() {
$total = 0;
foreach ($_SESSION['cart'] as $item) {
$total += $item['details']['price'] * $item['quantity'];
}
return number_format($total, 2);
}
清空购物车
重置 Session 中的购物车数组为空。
function clearCart() {
$_SESSION['cart'] = [];
}
显示购物车内容
通过循环输出商品列表,可结合 HTML 表格展示。
function displayCart() {
if (empty($_SESSION['cart'])) {
echo "购物车为空";
return;
}
echo "<table border='1'><tr><th>商品</th><th>单价</th><th>数量</th><th>小计</th></tr>";
foreach ($_SESSION['cart'] as $id => $item) {
$subtotal = $item['details']['price'] * $item['quantity'];
echo "<tr>
<td>{$item['details']['name']}</td>
<td>\${$item['details']['price']}</td>
<td>{$item['quantity']}</td>
<td>\$" . number_format($subtotal, 2) . "</td>
</tr>";
}
echo "</table>";
echo "<p>总计: \$" . calculateTotal() . "</p>";
}
安全注意事项
- 对用户输入进行过滤验证,防止 Session 固定攻击
- 重要操作如结算时应验证用户登录状态
- 敏感数据如价格应存储在服务端,避免前端篡改
// 示例:验证商品ID为整数
$productId = filter_input(INPUT_GET, 'product_id', FILTER_VALIDATE_INT);
if ($productId === false) {
die("Invalid product ID");
}
完整流程示例
典型购物车操作流程包含添加、更新、删除和显示功能,通过表单或 AJAX 与后端交互。
// 处理表单提交
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (isset($_POST['add_item'])) {
addToCart($_POST['product_id'], $_POST['quantity'], [
'name' => $_POST['product_name'],
'price' => $_POST['product_price']
]);
}
elseif (isset($_POST['remove_item'])) {
removeFromCart($_POST['product_id']);
}
elseif (isset($_POST['update_quantity'])) {
updateQuantity($_POST['product_id'], $_POST['new_quantity']);
}
elseif (isset($_POST['clear_cart'])) {
clearCart();
}
header("Location: ".$_SERVER['PHP_SELF']);
exit;
}






