萬盛學電腦網

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

PHP 購物車類:Cookie 儲存版完整實作與改進指南

基於 Cookie 的輕量級購物車實作

適合中小型專案、無需資料庫即可快速上線的購物車方案。資料結構採用 type:id,id|type:id,id 格式儲存於 Cookie,支援商品分類、防重複、刪除、清空等操作。本文重構原始碼,修正語法錯誤、加入型別宣告、修正正則逸出問題,並補充數量管理擴充方向。

資料結構說明

Cookie 名稱: cart
值範例: "food:101,102|electronics:205|books:301,302,303"
結構: 類型:ID,ID|類型:ID|...

重構後的 Cart 類別

<?php
class Cart
{
    private const COOKIE_NAME = 'cart';
    private const COOKIE_EXPIRE = 86400 * 30; // 30 天

    /** 新增商品 */
    public static function add(string $type, string $id): void
    {
        $cart = self::getCartData();
        $key = self::findTypeKey($cart, $type);

        if ($key === null) {
            $cart[] = "$type:$id";
        } else {
            $ids = explode(',', $cart[$key]);
            if (!in_array($id, $ids, true)) {
                $ids[] = $id;
                $cart[$key] = $type . ':' . implode(',', $ids);
            }
        }
        self::saveCart($cart);
    }

    /** 取得指定類型的商品 ID 陣列 */
    public static function getIds(string $type): array
    {
        $cart = self::getCartData();
        $key = self::findTypeKey($cart, $type);
        if ($key === null) return [];
        return explode(',', $cart[$key]);
    }

    /** 刪除指定商品 */
    public static function remove(string $type, string $id): void
    {
        $cart = self::getCartData();
        $key = self::findTypeKey($cart, $type);
        if ($key === null) return;

        $ids = explode(',', $cart[$key]);
        $ids = array_filter($ids, fn($v) => $v !== $id);

        if (empty($ids)) {
            unset($cart[$key]);
            $cart = array_values($cart); // 重建索引
        } else {
            $cart[$key] = $type . ':' . implode(',', $ids);
        }
        self::saveCart($cart);
    }

    /** 清空購物車 */
    public static function clear(): void
    {
        setcookie(self::COOKIE_NAME, '', time() - 3600, '/');
    }

    /** 取得完整購物車資料(供前端顯示) */
    public static function getAll(): array
    {
        $cart = self::getCartData();
        $result = [];
        foreach ($cart as $item) {
            [$type, $idsStr] = explode(':', $item, 2);
            $result[$type] = explode(',', $idsStr);
        }
        return $result;
    }

    // ===== 私有輔助方法 =====
    private static function getCartData(): array
    {
        $cookie = $_COOKIE[self::COOKIE_NAME] ?? '';
        return $cookie ? explode('|', $cookie) : [];
    }

    private static function findTypeKey(array $cart, string $type): ?int
    {
        foreach ($cart as $i => $item) {
            if (str_starts_with($item, $type . ':')) {
                return $i;
            }
        }
        return null;
    }

    private static function saveCart(array $cart): void
    {
        $value = implode('|', $cart);
        setcookie(self::COOKIE_NAME, $value, time() + self::COOKIE_EXPIRE, '/', '', false, true); // HttpOnly=true
    }
}

使用範例

<?php
require_once 'Cart.php';

// 新增商品
Cart::add('food', '101');
Cart::add('food', '102');
Cart::add('electronics', '205');

// 顯示購物車
$cart = Cart::getAll();
foreach ($cart as $type => $ids) {
    echo "

$type

    "; foreach ($ids as $id) { echo "
  • 商品 ID: $id
  • "; } echo "
"; } // 刪除商品 Cart::remove('food', '101'); // 清空 // Cart::clear();

擴充方向:加入數量與價格

若需支援數量、單價、小計,建議改用 JSON 結構儲存:

[
  {"type": "food", "id": "101", "qty": 2, "price": 120},
  {"type": "electronics", "id": "205", "qty": 1, "price": 3500}
]

對應修改 saveCart 序列化為 json_encode,getCartData 反序列化 json_decode,並調整 add/remove/getIds 邏輯即可。Cookie 容量限制 4KB,商品過多時建議改用 Session + 資料庫方案。

安全性補充

  • Cookie 設定 HttpOnly、Secure (HTTPS)、SameSite=Lax。
  • 前端顯示前務必驗證商品 ID 是否存在於資料庫,防止偽造 ID 攻擊。
  • 敏感操作(結帳)需二次驗證使用者身份,不可僅信任 Cookie 資料。
copyright © 萬盛學電腦網 all rights reserved