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

PHP 購物車實現:Session + 文件存儲完整源碼(無數據庫)

     編輯:PHP 相關知識

PHP 購物車實現:Session + 文件存儲完整源碼(無數據庫)

輕量級電商項目或原型驗證,可用 Session 管理購物車狀態,文本文件存儲商品數據,無需數據庫即可運行完整的加入、查看、修改、結算流程。

文件結構

cart/
├── lib.inc.php       # 商品數據加載(文本文件解析)
├── add_item.php      # 加入購物車
├── cart.php          # 查看/修改購物車
├── change_quant.php  # 修改數量
├── products.txt      # 商品數據文件
└── session_id/       # 單點登錄用(可選)

1. 商品數據層 (lib.inc.php)

<?php
// 商品數據緩存
$master_products_list = [];

/**
 * 從 products.txt 加載商品數據
 * 格式:ID|名稱|描述|價格(每行一條)
 * 例:1|iPhone 15|最新旗艦手機|7999
 */
function LoadProducts() {
    global $master_products_list;
    $filename = 'products.txt';
    
    $fp = @fopen($filename, 'r') or die("無法打開 $filename");
    @flock($fp, LOCK_SH) or die("無法鎖定 $filename");
    
    while ($line = fgets($fp, 1024)) {
        $line = trim($line);
        if (!$line) continue;
        list($id, $name, $desc, $price) = explode('|', $line);
        $id = trim($id);
        $master_products_list[$id] = [
            'name'  => $name,
            'desc'  => $desc,
            'price' => (float)$price
        ];
    }
    
    @fclose($fp);
}
?>

products.txt 示例

1|iPhone 15 Pro|256GB 深空黑|7999
2|MacBook Pro 14|M3 Pro 18GB 512GB|15999
3|AirPods Pro 2|主動降噪|1899
4|iPad Air|64GB 紫色|4399
5|Apple Watch S9|45mm 鋁殼|2999

2. 加入購物車 (add_item.php)

<?php
session_start();
require 'lib.inc.php';
LoadProducts();

$productId = $_GET['id'] ?? '';
$quantity = (int)($_POST['quantity'] ?? 1);

// 獲取商品信息
$product = $master_products_list[$productId] ?? null;
if (!$product) die("商品不存在");

if ($_POST) {
    // 加入購物車
    if (!isset($_SESSION['cart'])) {
        $_SESSION['cart'] = ['items' => [], 'total_qty' => 0, 'total_price' => 0];
    }
    
    $cart = &$_SESSION['cart'];
    
    // 已存在則累加數量
    if (isset($cart['items'][$productId])) {
        $cart['items'][$productId]['qty'] += $quantity;
    } else {
        $cart['items'][$productId] = [
            'name'  => $product['name'],
            'price' => $product['price'],
            'qty'   => $quantity
        ];
    }
    
    $cart['total_qty'] += $quantity;
    $cart['total_price'] += $product['price'] * $quantity;
    
    header('Location: cart.php');
    exit;
}
?>
<!DOCTYPE html>
<html><head><meta charset="utf-8"><title>加入購物車</title></head><body>
<h2>確認添加:<?= $product['name'] ?></h2>
<p>價格:¥<?= $product['price'] ?></p>
<p>描述:<?= $product['desc'] ?></p>
<form method="post">
    數量:<input type="number" name="quantity" value="1" min="1" max="99">
    <input type="hidden" name="id" value="<?= $productId ?>">
    <button type="submit">加入購物車</button>
</form>
<a href="cart.php">查看購物車</a>
</body></html>

3. 購物車頁面 (cart.php)

<?php
session_start();
require 'lib.inc.php';
LoadProducts();

$cart = $_SESSION['cart'] ?? ['items' => [], 'total_qty' => 0, 'total_price' => 0];
?>
<!DOCTYPE html>
<html><head><meta charset="utf-8"><title>購物車</title></head><body>
<h1>購物車 <small>(<?= $cart['total_qty'] ?> 件)</small></h1>

<?php if ($cart['items']): ?>
<table border="1" cellpadding="8" cellspacing="0">
    <tr><th>商品</th><th>單價</th><th>數量</th><th>小計</th><th>操作</th></tr>
    <?php foreach ($cart['items'] as $id => $item): ?>
    <tr>
        <td><?= $item['name'] ?></td>
        <td>¥<?= $item['price'] ?></td>
        <td>
            <form action="change_quant.php" method="post" style="display:inline">
                <input type="hidden" name="id" value="<?= $id ?>">
                <input type="number" name="quantity" value="<?= $item['qty'] ?>" min="0" max="99" style="width:60px">
                <button type="submit">更新</button>
            </form>
        </td>
        <td>¥<?= $item['price'] * $item['qty'] ?></td>
        <td>
            <form action="change_quant.php" method="post" style="display:inline">
                <input type="hidden" name="id" value="<?= $id ?>">
                <input type="hidden" name="quantity" value="0">
                <button type="submit" onclick="return confirm('確定刪除?')">刪除</button>
            </form>
        </td>
    </tr>
    <?php endforeach; ?>
    <tr>
        <td colspan="3" align="right"><strong>合計</strong></td>
        <td><strong>¥<?= $cart['total_price'] ?></strong></td>
        <td></td>
    </tr>
</table>
<p><a href="checkout.php">去結算</a> | <a href="index.php">繼續購物</a></p>
<?php else: ?>
<p>購物車是空的</p>
<p><a href="index.php">去選購商品</a></p>
<?php endif; ?>
</body></html>

4. 修改數量 (change_quant.php)

<?php
session_start();

$id = $_POST['id'] ?? '';
$quantity = (int)($_POST['quantity'] ?? 0);

if (!isset($_SESSION['cart']['items'][$id])) {
    header('Location: cart.php');
    exit;
}

$cart = &$_SESSION['cart'];
$oldQty = $cart['items'][$id]['qty'];
$price = $cart['items'][$id]['price'];

if ($quantity > 0) {
    $cart['items'][$id]['qty'] = $quantity;
    $cart['total_qty'] += $quantity - $oldQty;
    $cart['total_price'] += $price * ($quantity - $oldQty);
} else {
    // 數量為 0 視為刪除
    unset($cart['items'][$id]);
    $cart['total_qty'] -= $oldQty;
    $cart['total_price'] -= $price * $oldQty;
}

header('Location: cart.php');
?>

5. 結算頁面 (checkout.php) - 簡化版

<?php
session_start();
$cart = $_SESSION['cart'] ?? ['items' => [], 'total_price' => 0];

if (!$cart['items']) {
    header('Location: cart.php');
    exit;
}

if ($_POST) {
    // 處理訂單:保存訂單、發送郵件、調用支付接口、清空購物車
    $orderId = 'ORD_' . date('YmdHis') . rand(1000, 9999);
    // TODO: 保存訂單到文件/數據庫
    unset($_SESSION['cart']);
    echo "<h2>訂單提交成功!訂單號:$orderId</h2>";
    echo "<a href='index.php'>返回首頁</a>";
    exit;
}
?>
<!DOCTYPE html>
<html><head><meta charset="utf-8"><title>結算</title></head><body>
<h1>確認訂單</h1>
<table border="1" cellpadding="8">
    <tr><th>商品</th><th>數量</th><th>小計</th></tr>
    <?php foreach ($cart['items'] as $item): ?>
    <tr>
        <td><?= $item['name'] ?></td>
        <td><?= $item['qty'] ?></td>
        <td>¥<?= $item['price'] * $item['qty'] ?></td>
    </tr>
    <?php endforeach; ?>
    <tr><td colspan="2" align="right"><strong>總計</strong></td><td><strong>¥<?= $cart['total_price'] ?></strong></td></tr>
</table>
<form method="post">
    <p>收貨地址:<textarea name="address" required></textarea></p>
    <p>聯系電話:<input name="phone" required></p>
    <button type="submit">提交訂單</button>
</form>
</body></html>

生產環境升級路徑

模塊當前升級目標
商品存儲文本文件MySQL/PostgreSQL + 索引
Session 存儲文件Redis Cluster
併發控制無Redis Lua 腳本 / 數據庫樂觀鎖
價格精度floatDecimal / 整數分
庫存扣減無Redis 原子遞減 + 數據庫最終一致
會話共享單機多機 Session 同步 / JWT 無狀態

安全補充

  • CSRF Token:所有表單添加 <input type="hidden" name="_token" value="">
  • XSS 防護:輸出轉義 htmlspecialchars()
  • 價格篡改:服務端重新計算總價,不信任前端提交金額
  • 數量限制:單商品最大購買量、庫存實時校驗

這個無數據庫購物車通過 Session + 文本文件實現了核心電商流程,代碼清晰、部署即用,適合 MVP 驗證、內部採購、教學演示。生產環境請按升級路徑逐步重構。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved