為中小型電商項目快速構建購物車功能,本文提供一套基於 PHP Session + 文本文件存儲的完整實現,包含商品列表、加入購物車、查看/修改/刪除購物車、結算流程,無需數據庫即可運行。
cart/ ├── index.php # 商品列表 + 購物車顯示 ├── add.php # 加入購物車 ├── update.php # 修改數量 ├── delete.php # 刪除商品 ├── lib.inc.php # 共用函數(載入商品、Session 初始化) ├── products.txt # 商品數據(CSV 格式) └── carts/ # 用戶購物車文件目錄(以 session_id 命名)
<?php
session_start();
// 載入商品主檔
function loadProducts() {
static $products = null;
if ($products !== null) return $products;
$file = __DIR__ . '/products.txt';
$products = [];
if (file_exists($file)) {
$lines = file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
foreach ($lines as $line) {
[$id, $name, $desc, $price] = array_map('trim', explode(',', $line));
$products[$id] = ['name'=>$name, 'desc'=>$desc, 'price'=>(float)$price];
}
}
return $products;
}
// 初始化購物車
function initCart() {
if (!isset($_SESSION['cart'])) {
$_SESSION['cart'] = ['items'=>[], 'total_qty'=>0, 'total_amount'=>0.0];
}
return &$_SESSION['cart'];
}
// 重新計算總計
function recalcCart(&$cart, $products) {
$cart['total_qty'] = 0;
$cart['total_amount'] = 0.0;
foreach ($cart['items'] as $id => $qty) {
if (isset($products[$id])) {
$cart['total_qty'] += $qty;
$cart['total_amount'] += $qty * $products[$id]['price'];
}
}
}
// 保存購物車到文件(可選,Session 已持久化)
function saveCartToFile($cart) {
$dir = __DIR__ . '/carts/';
if (!is_dir($dir)) mkdir($dir, 0755, true);
$file = $dir . session_id() . '.txt';
file_put_contents($file, serialize($cart));
}
?>
P001,智能手機,最新款旗艦機,5999.00
P002,藍牙耳機,降噪運動款,399.00
P003,手機殼,透明防摔,29.90
P004,充電寶,20000mAh快充,129.00
<?php require 'lib.inc.php';
$products = loadProducts();
$cart = initCart();
recalcCart($cart, $products);
?>
<!DOCTYPE html>
<html><head><meta charset="utf-8"><title>簡易購物車</title></head><body>
<h1>商品列表</h1>
<table border="1" cellpadding="5">
<tr><th>名稱</th><th>說明</th><th>價格</th><th>操作</th></tr>
<?php foreach ($products as $id => $p): ?>
<tr>
<td><?= htmlspecialchars($p['name']) ?></td>
<td><?= htmlspecialchars($p['desc']) ?></td>
<td>¥<?= number_format($p['price'],2) ?></td>
<td><a href="add.php?id=<?= $id ?>">加入購物車</a></td>
</tr>
<?php endforeach; ?>
</table>
<hr><h2>我的購物車 (共 <?= $cart['total_qty'] ?> 件,¥<?= number_format($cart['total_amount'],2) ?>)</h2>
<?php if (empty($cart['items'])): ?>
<p>購物車為空</p>
<?php else: ?>
<form action="update.php" method="post">
<table border="1" cellpadding="5">
<tr><th>商品</th><th>單價</th><th>數量</th><th>小計</th><th>操作</th></tr>
<?php foreach ($cart['items'] as $id => $qty):
$p = $products[$id];
$subtotal = $qty * $p['price'];
?>
<tr>
<td><?= htmlspecialchars($p['name']) ?></td>
<td>¥<?= number_format($p['price'],2) ?></td>
<td><input type="number" name="qty[<?= $id ?>]" value="<?= $qty ?>" min="1" max="99" style="width:60px"></td>
<td>¥<?= number_format($subtotal,2) ?></td>
<td><a href="delete.php?id=<?= $id ?>" onclick="return confirm('確定刪除?')">刪除</a></td>
</tr>
<?php endforeach; ?>
<tr>
<td colspan="3" align="right">合計:</strong></td>
<td>¥<?= number_format($cart['total_amount'],2) ?></strong></td>
<td><button type="submit">更新數量</button></td>
</tr>
</table>
</form>
<p><a href="checkout.php">去結算</a></p>
<?php endif; ?>
</body></html>
<?php // add.php
require 'lib.inc.php';
$products = loadProducts();
$cart = initCart();
$id = $_GET['id'] ?? '';
if ($id && isset($products[$id])) {
$cart['items'][$id] = ($cart['items'][$id] ?? 0) + 1;
recalcCart($cart, $products);
saveCartToFile($cart);
header('Location: index.php?added=1');
exit;
}
die('商品不存在');
<?php // update.php
require 'lib.inc.php';
$products = loadProducts();
$cart = initCart();
if ($_POST['qty']) {
foreach ($_POST['qty'] as $id => $qty) {
$qty = max(1, (int)$qty);
if (isset($cart['items'][$id])) $cart['items'][$id] = $qty;
}
recalcCart($cart, $products);
saveCartToFile($cart);
}
header('Location: index.php');
<?php // delete.php
require 'lib.inc.php';
$cart = initCart();
$id = $_GET['id'] ?? '';
if ($id && isset($cart['items'][$id])) {
unset($cart['items'][$id]);
$products = loadProducts();
recalcCart($cart, $products);
saveCartToFile($cart);
}
header('Location: index.php');
此方案代碼總量 < 200 行,零依賴、零配置即可運行,極適合原型驗證、教學演示、微型電商項目快速起步。