萬盛學電腦網

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

PHP 檔案操作實戰:建立簡易留言板系統(含完整代碼)

專案概述

本文透過一個完整的留言板範例,示範 PHP 基礎檔案操作:目錄掃描、檔案讀寫、資料序列化、表單處理。適用於初學者理解檔案系統操作,或無資料庫環境的輕量應用。

系統架構設計

  • 資料儲存:每則留言一個檔案,儲於 DB/ 目錄,檔名含時間戳確保唯一
  • 檔案格式:純文字,每行一欄位(標題、作者、內容),簡單易讀
  • 安全考量:輸出轉義防 XSS、檔名過濾防目錄遍歷、輸入長度限制

目錄結構

guestbook/
├── index.php      # 留言列表頁
├── post.php       # 發表處理
├── form.html      # 發表表單
├── style.css      # 簡易樣式
└── DB/            # 留言資料目錄 (需寫入權限)
    ├── S20240115103000.dat
    └── S20240115103500.dat

核心程式碼實作

1. 留言列表 - index.php

<?php
// index.php
declare(strict_types=1);

// 配置
const DATA_DIR = __DIR__ . '/DB';
const MAX_MESSAGES = 100; // 最大留言數,防止無限增長

// 確保資料目錄存在
if (!is_dir(DATA_DIR)) {
    mkdir(DATA_DIR, 0755, true);
}

// 讀取所有留言檔案
$messages = [];
$files = glob(DATA_DIR . '/*.dat');

// 依檔名倒序排序 (最新在前)
rsort($files);

// 限制顯示數量
$files = array_slice($files, 0, MAX_MESSAGES);

foreach ($files as $file) {
    $lines = file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    if (count($lines) >= 3) {
        $messages[] = [
            'title'   => htmlspecialchars($lines[0] ?? ''),
            'author'  => htmlspecialchars($lines[1] ?? ''),
            'content' => htmlspecialchars($lines[2] ?? ''),
            'time'    => date('Y-m-d H:i:s', filemtime($file)),
        ];
    }
}
?>
<!DOCTYPE html>
<html lang="zh-TW">
<head>
    <meta charset="UTF-8">
    <title>簡易留言板</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <div class="container">
        <header>
            <h1>📝 簡易留言板</h1>
            <a href="form.html" class="btn-new">+ 發表新留言</a>
        </header>

        <?php if (empty($messages)): ?>
            <div class="empty-state">目前沒有留言,快來搶第一沙發!</div>
        <?php else: ?>
            <?php foreach ($messages as $msg): ?>
                <article class="message">
                    <header class="message-header">
                        <h2><?= $msg['title'] ?></h2>
                        <div class="meta">
                            <span class="author">👤 <?= $msg['author'] ?></span>
                            <span class="time">🕒 <?= $msg['time'] ?></span>
                        </div>
                    </header>
                    <div class="content"><?= nl2br($msg['content']) ?></div>
                </article>
            <?php endforeach; ?>
        <?php endif; ?>
    </div>
</body></html>

2. 發表表單 - form.html

<!DOCTYPE html>
<html lang="zh-TW">
<head>
    <meta charset="UTF-8">
    <title>發表留言</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <div class="container">
        <header>
            <h1>✍️ 發表新留言</h1>
            <a href="index.php" class="btn-back">← 返回列表</a>
        </header>

        <form action="post.php" method="POST" class="message-form">
            <div class="form-group">
                <label for="title">標題 *</label>
                <input type="text" id="title" name="title" maxlength="100" required placeholder="輸入留言標題">
            </div>

            <div class="form-group">
                <label for="author">暱稱 *</label>
                <input type="text" id="author" name="author" maxlength="30" required placeholder="您的暱稱">
            </div>

            <div class="form-group">
                <label for="content">內容 *</label>
                <textarea id="content" name="content" rows="8" maxlength="2000" required placeholder="分享您的想法..."></textarea>
                <small class="hint">最多 2000 字</small>
            </div>

            <button type="submit" class="btn-submit">發表留言</button>
        </form>
    </div>
</body></html>

3. 發表處理 - post.php

<?php
// post.php
declare(strict_types=1);

const DATA_DIR = __DIR__ . '/DB';
const MAX_TITLE_LEN = 100;
const MAX_AUTHOR_LEN = 30;
const MAX_CONTENT_LEN = 2000;
const MAX_MESSAGES = 100;

// 確保目錄存在
if (!is_dir(DATA_DIR)) {
    mkdir(DATA_DIR, 0755, true);
}

// 僅接受 POST
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    exit('方法不允許');
}

// 取得並驗證輸入
$title = trim($_POST['title'] ?? '');
$author = trim($_POST['author'] ?? '');
$content = trim($_POST['content'] ?? '');

$errors = [];
if ($title === '') $errors[] = '標題不可為空';
if (mb_strlen($title) > MAX_TITLE_LEN) $errors[] = "標題不超過 $MAX_TITLE_LEN 字";

if ($author === '') $errors[] = '暱稱不可為空';
if (mb_strlen($author) > MAX_AUTHOR_LEN) $errors[] = "暱稱不超過 $MAX_AUTHOR_LEN 字";

if ($content === '') $errors[] = '內容不可為空';
if (mb_strlen($content) > MAX_CONTENT_LEN) $errors[] = "內容不超過 $MAX_CONTENT_LEN 字";

if (!empty($errors)) {
    http_response_code(400);
    echo '<div class="error"><h3>發表失敗:</h3><ul>';
    foreach ($errors as $e) echo "<li>" . htmlspecialchars($e) . "</li>";
    echo '</ul><a href="form.html">返回修正</a></div>';
    exit;
}

// 防止目錄遍歷:檔名僅使用時間戳 + 隨機數
$filename = 'S' . date('YmdHis') . '_' . mt_rand(1000, 9999) . '.dat';
$filepath = DATA_DIR . '/' . $filename;

// 寫入檔案 (獨佔鎖定防止併發衝突)
$fp = fopen($filepath, 'wb');
if ($fp === false) {
    http_response_code(500);
    exit('無法建立留言檔案,請檢查目錄權限');
}

flock($fp, LOCK_EX);
fwrite($fp, $title . "\n");
fwrite($fp, $author . "\n");
fwrite($fp, $content . "\n");
flock($fp, LOCK_UN);
fclose($fp);

// 維護:清理舊留言 (保留最新 MAX_MESSAGES 筆)
$files = glob(DATA_DIR . '/*.dat');
if (count($files) > MAX_MESSAGES) {
    usort($files, fn($a, $b) => filemtime($a) <=> filemtime($b));
    $toDelete = array_slice($files, 0, count($files) - MAX_MESSAGES);
    foreach ($toDelete as $f) @unlink($f);
}

// 成功導向
header('Location: index.php?success=1');
exit;

4. 樣式 - style.css

/* style.css */
* { box-sizing: border-box; margin: 0; padding: 0; }
body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Microsoft JhengHei", sans-serif; line-height: 1.6; background: #f5f5f5; color: #333; padding: 20px; }
.container { max-width: 700px; margin: 0 auto; background: white; border-radius: 8px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); overflow: hidden; }
header { display: flex; justify-content: space-between; align-items: center; padding: 20px; border-bottom: 1px solid #eee; background: #fafafa; }
h1 { font-size: 1.5rem; }
.btn-new, .btn-back { color: #007bff; text-decoration: none; font-weight: 500; }
.btn-new:hover, .btn-back:hover { text-decoration: underline; }
.empty-state { padding: 40px; text-align: center; color: #999; }
.message { border-bottom: 1px solid #eee; padding: 20px; }
.message:last-child { border-bottom: none; }
.message-header { margin-bottom: 12px; }
.message-header h2 { font-size: 1.1rem; margin-bottom: 8px; }
.meta { display: flex; gap: 16px; font-size: 0.85rem; color: #666; }
.content { white-space: pre-wrap; word-break: break-word; }
.message-form { padding: 20px; }
.form-group { margin-bottom: 16px; }
.form-group label { display: block; margin-bottom: 6px; font-weight: 500; }
.form-group input, .form-group textarea { width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 4px; font-family: inherit; font-size: 1rem; }
.form-group input:focus, .form-group textarea:focus { outline: none; border-color: #007bff; box-shadow: 0 0 0 3px rgba(0,123,255,0.15); }
.hint { color: #999; font-size: 0.85rem; }
.btn-submit { width: 100%; padding: 12px; background: #007bff; color: white; border: none; border-radius: 4px; font-size: 1rem; font-weight: 600; cursor: pointer; }
.btn-submit:hover { background: #0056b3; }
.error { padding: 20px; background: #fff3f3; border: 1px solid #ffcccc; color: #cc0000; }
.error ul { margin: 10px 0 0 20px; }

安全性強化重點

  1. 輸出轉義:htmlspecialchars() 防 XSS,nl2br() 保留換行
  2. 檔名安全:不使用用戶輸入作檔名,改用時間戳+隨機數
  3. 檔案鎖定:flock() 防併發寫入損壞資料
  4. 輸入長度限制:前後端雙重驗證,防止撐爆磁碟
  5. 資料清理:定期清理舊留言,避免 inode 耗盡

擴充建議

  • JSON 格式:改用 json_encode() 儲存,支援巢狀資料、編輯、刪除、回覆功能
  • 分頁載入:AJAX 無限滾動載入,避免一次讀取大量檔案
  • 圖片上傳:整合檔案上傳,生成縮圖儲存
  • 管理後台:密碼保護的刪除/編輯介面
  • 遷移資料庫:資料量大時無縫遷移至 SQLite/MySQL

總結

這個留言板範例雖簡單,但涵蓋了 PHP 檔案操作的核心技巧:glob() 掃描、file() 讀取、fopen()/fwrite()/flock() 安全寫入、目錄維護。理解這些基礎,才能在需要時靈活選擇「檔案 vs 資料庫」,也能看懂框架底層的儲存實作原理。

copyright © 萬盛學電腦網 all rights reserved