首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

PHP 簡易購物車實作:Session 管理、文字檔商品資料、完整流程

     編輯:PHP 相關知識

架構設計

不使用資料庫,商品資料存放於 products.txt(管線分隔),購物車狀態儲存於 $_SESSION['cart']。包含四個檔案:lib.inc.php(商品載入)、add_item.php(加入購物車)、cart.php(檢視/修改/商品列表)、change_quant.php(數量變更)。

商品資料格式 (products.txt)

1|產品A|產品A說明|100
2|產品B|產品B說明|250
3|產品C|產品C說明|320

核心函式庫 (lib.inc.php)

 $name,
            "desc" => $desc,
            "price" => $price
        );
    }
    @fclose($fp) or die("無法關閉 $filename");
}

加入購物車 (add_item.php)

0, 'products'=>array());
require 'lib.inc.php';
LoadProducts();

$curr_product = array();
foreach ($master_products_list as $pid => $product) {
    if (trim($pid) == trim($_GET['id'])) $curr_product = $product;
}

if (isset($_POST['ordered'])) {
    array_push($_SESSION['cart']['products'], array(trim($_POST['id']), (int)$_POST['quantity']));
    $_SESSION['cart']['num_items'] += (int)$_POST['quantity'];
    // 導向購物車頁或顯示成功訊息
}
?>

購物車檢視與商品列表 (cart.php)

0, 'products'=>array());
require 'lib.inc.php';
LoadProducts();
?>


歡迎光臨網路商店

購物車內容

$item) { $pid = $item[0]; $qty = $item[1]; $p = $master_products_list[$pid]; $subtotal = $qty * $p['price']; $total += $subtotal; ?>
商品說明單價數量操作
總計:

商品列表

$item): ?>
商品說明價格動作
$ 加入購物車

數量變更 (change_quant.php)

0, 'products'=>array());

$i = (int)$_POST['id'];
$old_qty = $_SESSION['cart']['products'][$i][1] ?? 0;
$new_qty = (int)$_POST['quantity'];

if ($new_qty > 0) {
    $_SESSION['cart']['products'][$i][1] = $new_qty;
} else {
    unset($_SESSION['cart']['products'][$i]);
}

// 重新計算總數量
$_SESSION['cart']['num_items'] = 0;
foreach ($_SESSION['cart']['products'] as $item) {
    $_SESSION['cart']['num_items'] += $item[1];
}
header("Location: cart.php");

資料結構說明


$_SESSION['cart'] = [
    'num_items' => 5,                    // 總商品件數
    'products' => [                      // 索引陣列,每項為 [商品ID, 數量]
        ['1', 2],
        ['3', 3]
    ]
];

安全性與擴充建議

問題風險解決方案
Session 劫持購物車被盜用HTTPS 強制、HttpOnly Cookie、Session ID 重生成
商品價格竄改前端修改價格送單下單時後端重新查詢價格,不信任前端傳值
文字檔併發多進程讀寫衝突flock(Lcok_SH/EX)、遷移至 SQLite/Redis/MySQL
無庫存控制超賣加入庫存欄位,下單時扣減(需交易鎖)
Session 失效遺失使用者關閉瀏覽器車清空登入會員綁定資料庫持久化購物車

現代化重構方向

  1. 資料庫化:商品表、購物車表、訂單表,支援併發、索引、關聯查詢
  2. API 化:前後端分離,Vue/React 呼叫 RESTful API(加入、列表、更新、刪除)
  3. 狀態管理:Redis 儲存購物車(Hash 結構),支援多裝置同步、TTL 自動清理
  4. 事件驅動:加入購物車發送事件,觸發推薦、庫存預留、分析日誌
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved