本文透過一個完整的留言板範例,示範 PHP 基礎檔案操作:目錄掃描、檔案讀寫、資料序列化、表單處理。適用於初學者理解檔案系統操作,或無資料庫環境的輕量應用。
DB/ 目錄,檔名含時間戳確保唯一guestbook/
├── index.php # 留言列表頁
├── post.php # 發表處理
├── form.html # 發表表單
├── style.css # 簡易樣式
└── DB/ # 留言資料目錄 (需寫入權限)
├── S20240115103000.dat
└── S20240115103500.dat
<?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>
<!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>
<?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;
/* 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; }
htmlspecialchars() 防 XSS,nl2br() 保留換行flock() 防併發寫入損壞資料json_encode() 儲存,支援巢狀資料、編輯、刪除、回覆功能這個留言板範例雖簡單,但涵蓋了 PHP 檔案操作的核心技巧:glob() 掃描、file() 讀取、fopen()/fwrite()/flock() 安全寫入、目錄維護。理解這些基礎,才能在需要時靈活選擇「檔案 vs 資料庫」,也能看懂框架底層的儲存實作原理。