萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP Session 購物車完整實作:商品管理、數量修改、總價計算

前言

Session 是 PHP 實作購物車的經典方式,無需資料庫即可跨頁面保持狀態。本文完整實作一個功能齊全的 Session 購物車:商品列表、加入購物車、顯示明細、修改數量、移除商品、總價計算,並說明 Session 安全與擴充要點。

專案結構

shop/
├── config.php          # 設定檔
├── products.txt        # 商品資料 (文字檔模擬)
├── lib.inc.php         # 共用函數:載入商品、Session 初始化
├── index.php           # 商品列表 + 購物車顯示
├── add_item.php        # 加入購物車
├── change_quant.php    # 修改數量
└── cart.php            # 購物車頁面 (同 index.php)

核心共用函數 (lib.inc.php)

<?php
// 啟動 Session (所有頁面最前面)
session_start();

// 初始化購物車結構
if (!isset($_SESSION['cart'])) {
    $_SESSION['cart'] = [
        'num_items' => 0,
        'products'  => []  // [$index => [$productId, $quantity]]
    ];
}

// 載入商品資料 (從文字檔)
function loadProducts() {
    static $products = null;
    if ($products !== null) return $products;

    $file = __DIR__ . '/products.txt';
    if (!is_readable($file)) {
        die("無法讀取商品檔案: $file");
    }

    $products = [];
    $handle = fopen($file, 'r');
    while (($line = fgets($handle, 1024)) !== false) {
        $line = trim($line);
        if (!$line) continue;
        [$id, $name, $desc, $price] = explode('|', $line);
        $products[trim($id)] = [
            'name'  => $name,
            'desc'  => $desc,
            'price' => (float)$price,
        ];
    }
    fclose($handle);
    return $products;
}

// 格式化價格
function fmtPrice($price) {
    return number_format($price, 2);
}
?>

商品資料 (products.txt)

P001|筆記型電腦|高效能輕薄筆電|35000
P002|無線滑鼠|人體工學設計|800
P003|機械鍵盤|紅軸 RGB 背光|2500
P004|27吋螢幕|4K 解析度|12000
P005|USB-C 集線器|7合1 擴充|950

商品列表 + 購物車顯示 (index.php)

<?php
require 'lib.inc.php';
$products = loadProducts();
$cart = &$_SESSION['cart'];
$total = 0;
?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>購物車示範</title>
    <style>
        table { border-collapse: collapse; width: 100%; margin-bottom: 2rem; }
        th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
        th { background: #f4f4f4; }
        .price { text-align: right; }
    </style>
</head>
<body>
    <h1>歡迎光臨 PHP 購物商城</h1>

    <h2>🛒 目前購物車 (<?= $cart['num_items'] ?> 件)</h2>
    <?php if ($cart['num_items'] > 0): ?>
        <table>
            <tr><th>商品</th><th>說明</th><th class="price">單價</th>
                <th>數量</th><th class="price">小計</th><th>操作</th></tr>
            <?php foreach ($cart['products'] as $index => $item): 
                $pid = $item[0];
                $qty = $item[1];
                $p = $products[$pid];
                $subtotal = $p['price'] * $qty;
                $total += $subtotal;
            ?>
            <tr>
                <td><?= htmlspecialchars($p['name']) ?></td>
                <td><?= htmlspecialchars($p['desc']) ?></td>
                <td class="price">$<?= fmtPrice($p['price']) ?></td>
                <td>
                    <form action="change_quant.php" method="post" style="display:inline">
                        <input type="hidden" name="index" value="<?= $index ?>">
                        <input type="number" name="quantity" value="<?= $qty ?>" min="1" max="99" size="3">
                        <button type="submit">更新</button>
                    </form>
                </td>
                <td class="price">$<?= fmtPrice($subtotal) ?></td>
                <td>
                    <a href="change_quant.php?index=<?= $index ?>&quantity=0" onclick="return confirm('確定移除?')">🗑 移除</a>
                </td>
            </tr>
            <?php endforeach; ?>
            <tr>
                <td colspan="4" style="text-align:right">總計</strong></td>
                <td class="price">$<?= fmtPrice($total) ?></strong></td>
                <td></td>
            </tr>
        </table>
    <?php else: ?>
        <p>購物車是空的</p>
    <?php endif; ?>

    <hr>
    <h2>🛍 商品列表</h2>
    <table>
        <tr><th>商品</th><th>說明</th><th class="price">價格</th><th>操作</th></tr>
        <?php foreach ($products as $id => $p): ?>
        <tr>
            <td><?= htmlspecialchars($p['name']) ?></td>
            <td><?= htmlspecialchars($p['desc']) ?></td>
            <td class="price">$<?= fmtPrice($p['price']) ?></td>
            <td>
                <a href="add_item.php?id=<?= $id ?>">加入購物車</a>
            </td>
        </tr>
        <?php endforeach; ?>
    </table>
</body>
</html>

加入購物車 (add_item.php)

<?php
require 'lib.inc.php';
$products = loadProducts();

$id = $_GET['id'] ?? '';
if (!isset($products[$id])) {
    die("商品不存在: $id");
}
$product = $products[$id];
?>
<!DOCTYPE html>
<html>
<head><meta charset="utf-8"><title>加入購物車</title></head>
<body>
    <h1>加入 <?= htmlspecialchars($product['name']) ?> 到購物車</h1>
    <p>說明: <?= htmlspecialchars($product['desc']) ?></p>
    <p>單價: $<?= fmtPrice($product['price']) ?></p>
    
    <form method="post">
        <input type="hidden" name="id" value="<?= $id ?>">
        <label>數量: <input type="number" name="quantity" value="1" min="1" max="99"></label>
        <button type="submit">確定加入</button>
    </form>
    <p><a href="index.php">返回商品列表</a></p>
</body>
</html>

<?php
// 處理 POST 提交
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $id = $_POST['id'] ?? '';
    $qty = (int)($_POST['quantity'] ?? 1);
    
    if ($qty > 0 && isset($products[$id])) {
        // 檢查是否已在購物車
        $found = false;
        foreach ($_SESSION['cart']['products'] as $i => $item) {
            if ($item[0] === $id) {
                $_SESSION['cart']['products'][$i][1] += $qty;
                $found = true;
                break;
            }
        }
        if (!$found) {
            $_SESSION['cart']['products'][] = [$id, $qty];
        }
        $_SESSION['cart']['num_items'] += $qty;
        
        header('Location: index.php');
        exit;
    }
}
?>

修改數量 / 移除 (change_quant.php)

<?php
require 'lib.inc.php';

$index = (int)($_REQUEST['index'] ?? -1);
$qty   = (int)($_REQUEST['quantity'] ?? 0);

if ($index >= 0 && isset($_SESSION['cart']['products'][$index])) {
    $oldQty = $_SESSION['cart']['products'][$index][1];
    
    if ($qty > 0) {
        $_SESSION['cart']['products'][$index][1] = $qty;
        $_SESSION['cart']['num_items'] += ($qty - $oldQty);
        $msg = "數量已更新為 $qty";
    } else {
        // 移除商品
        unset($_SESSION['cart']['products'][$index]);
        $_SESSION['cart']['products'] = array_values($_SESSION['cart']['products']); // 重新索引
        $_SESSION['cart']['num_items'] -= $oldQty;
        $msg = "商品已移除";
    }
} else {
    $msg = "無效操作";
}

echo "<h1>$msg</h1>";
echo '<p><a href="index.php">返回購物車</a></p>';
?>

Session 安全與擴充建議

  1. Session 劫持防護:ini_set('session.cookie_httponly', 1); ini_set('session.cookie_secure', 1); // 僅 HTTPS
  2. Session 固定攻擊防護:登入後呼叫 session_regenerate_id(true)
  3. 大型購物車:改用資料庫儲存 (user_id + product_id + qty),Session 僅存 user_id
  4. 購物車持久化:登入用戶合併 Session 購物車至資料庫
  5. 庫存檢查:加入購物車/下單時即時檢查庫存、鎖定庫存
  6. 優惠碼/運費:擴充 cart 結構加入 coupons、shipping、discount 欄位

Session 設定最佳化 (php.ini / .user.ini)

; 使用 Redis 儲存 Session (高併發、分散式)
session.save_handler = redis
session.save_path = "tcp://127.0.0.1:6379"

; 安全設定
session.cookie_httponly = 1
session.cookie_secure = 1
session.cookie_samesite = Strict
session.use_strict_mode = 1
session.gc_maxlifetime = 1440  ; 24 分鐘
session.gc_probability = 1
session.gc_divisor = 100
copyright © 萬盛學電腦網 all rights reserved