架構設計
不使用資料庫,商品資料存放於 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;
?>
| = $p['name'] ?> |
= $p['desc'] ?> |
= $p['price'] ?> |
|
| 總計: | = $total ?> |
商品列表
| 商品 | 說明 | 價格 | 動作 |
$item): ?>
| = $item['name'] ?> |
= $item['desc'] ?> |
$= $item['price'] ?> |
加入購物車 |
數量變更 (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 失效遺失 | 使用者關閉瀏覽器車清空 | 登入會員綁定資料庫持久化購物車 |
現代化重構方向
- 資料庫化:商品表、購物車表、訂單表,支援併發、索引、關聯查詢
- API 化:前後端分離,Vue/React 呼叫 RESTful API(加入、列表、更新、刪除)
- 狀態管理:Redis 儲存購物車(Hash 結構),支援多裝置同步、TTL 自動清理
- 事件驅動:加入購物車發送事件,觸發推薦、庫存預留、分析日誌