專案架構規劃
1. 資料庫設計
2. 資料庫連線 (PDO)
<?php
// config/database.php
declare(strict_types=1);
class Database {
private static ?PDO $instance = null;
public static function getConnection(): PDO {
if (self::$instance === null) {
$dsn = 'mysql:host=127.0.0.1;dbname=guestbook;charset=utf8mb4';
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8mb4 COLLATE utf8mb4_unicode_ci",
];
self::$instance = new PDO($dsn, 'db_user', 'db_pass', $options);
}
return self::$instance;
}
}
?>
3. 留言模型與 Repository
<?php
// src/Message.php
declare(strict_types=1);
class Message {
public ?int $id;
public string $name;
public ?string $email;
public string $title;
public string $content;
public ?string $ip;
public ?string $userAgent;
public DateTime $createdAt;
public ?DateTime $updatedAt;
public static function fromArray(array $data): self {
$msg = new self();
$msg->id = $data['id'] ?? null;
$msg->name = $data['name'];
$msg->email = $data['email'] ?? null;
$msg->title = $data['title'];
$msg->content = $data['content'];
$msg->ip = $data['ip'] ?? null;
$msg->userAgent = $data['user_agent'] ?? null;
$msg->createdAt = new DateTime($data['created_at']);
$msg->updatedAt = $data['updated_at'] ? new DateTime($data['updated_at']) : null;
return $msg;
}
}
?>
<?php
// src/MessageRepository.php
declare(strict_types=1);
class MessageRepository {
private PDO $db;
public function __construct(PDO $db) {
$this->db = $db;
}
public function create(Message $message): int {
$sql = "INSERT INTO messages (name, email, title, content, ip, user_agent)
VALUES (:name, :email, :title, :content, :ip, :ua)";
$stmt = $this->db->prepare($sql);
$stmt->execute([
'name' => $message->name,
'email' => $message->email,
'title' => $message->title,
'content' => $message->content,
'ip' => $message->ip ? inet_pton($message->ip) : null,
'ua' => $message->userAgent,
]);
return (int)$this->db->lastInsertId();
}
public function findAll(int $limit = 50, int $offset = 0): array {
$sql = "SELECT * FROM messages ORDER BY created_at DESC LIMIT :limit OFFSET :offset";
$stmt = $this->db->prepare($sql);
$stmt->bindValue(':limit', $limit, PDO::PARAM_INT);
$stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
$stmt->execute();
return array_map([Message::class, 'fromArray'], $stmt->fetchAll());
}
public function count(): int {
return (int)$this->db->query('SELECT COUNT(*) FROM messages')->fetchColumn();
}
}
?>
4. 輸入驗證與清理
<?php
// src/Validator.php
declare(strict_types=1);
class Validator {
public static function validateMessage(array $input): array {
$errors = [];
$name = trim($input['name'] ?? '');
if ($name === '') $errors['name'] = '請輸入姓名';
elseif (mb_strlen($name) > 50) $errors['name'] = '姓名不超過 50 字元';
$email = trim($input['email'] ?? '');
if ($email !== '' && !filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors['email'] = '電子郵件格式不正確';
}
$title = trim($input['title'] ?? '');
if ($title === '') $errors['title'] = '請輸入標題';
elseif (mb_strlen($title) > 100) $errors['title'] = '標題不超過 100 字元';
$content = trim($input['content'] ?? '');
if ($content === '') $errors['content'] = '請輸入內容';
elseif (mb_strlen($content) > 5000) $errors['content'] = '內容不超過 5000 字元';
return [
'valid' => empty($errors),
'errors' => $errors,
'data' => $errors ? [] : [
'name' => $name,
'email' => $email ?: null,
'title' => $title,
'content' => $content,
]
];
}
}
?>
5. 控制器:新增留言
<?php
// public/create.php
require_once __DIR__ . '/../vendor/autoload.php'; // 或手動 include
use App\Config\Database;
use App\Src\Message;
use App\Src\MessageRepository;
use App\Src\Validator;
session_start();
$db = Database::getConnection();
$repo = new MessageRepository($db);
$errors = [];
$old = ['name'=>'', 'email'=>'', 'title'=>'', 'content'=>''];
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// CSRF 保護
if (!hash_equals($_SESSION['csrf'] ?? '', $_POST['csrf'] ?? '')) {
$errors['_form'] = '表單驗證失效,請重新整理';
} else {
$result = Validator::validateMessage($_POST);
if ($result['valid']) {
$msg = new Message();
$msg->name = $result['data']['name'];
$msg->email = $result['data']['email'];
$msg->title = $result['data']['title'];
$msg->content = $result['data']['content'];
$msg->ip = $_SERVER['REMOTE_ADDR'];
$msg->userAgent = $_SERVER['HTTP_USER_AGENT'] ?? '';
$repo->create($msg);
header('Location: index.php?success=1');
exit;
}
$errors = $result['errors'];
$old = $_POST;
}
}
// 產生新 CSRF Token
$_SESSION['csrf'] = bin2hex(random_bytes(32));
?>
發表留言
發表留言
= htmlspecialchars($errors['_form']) ?>
6. 控制器:留言列表 (分頁)
<?php
// public/index.php
require_once __DIR__ . '/../vendor/autoload.php';
use App\Config\Database;
use App\Src\MessageRepository;
$db = Database::getConnection();
$repo = new MessageRepository($db);
$page = max(1, (int)($_GET['page'] ?? 1));
$perPage = 10;
$total = $repo->count();
$totalPages = (int)ceil($total / $perPage);
$page = min($page, $totalPages ?: 1);
$offset = ($page - 1) * $perPage;
$messages = $repo->findAll($perPage, $offset);
?>
留言板
7. 安全性檢查清單 (上線前必做)
- ✅ 使用 PDO 參數綁定防 SQL 注入
- ✅ 輸出一律
htmlspecialchars() 防 XSS
- ✅ CSRF Token 保護表單
- ✅ 輸入長度/格式驗證
- ✅ 限制發文頻率 (IP/Session 級)
- ✅ 敏感詞過濾
- ✅ HTTPS 強制啟用
- ✅ 資料庫帳號最小權限
- ✅ 錯誤訊息不洩露堆疊追蹤
- ✅ 定期備份資料庫
擴充功能建議
- 回覆/巢狀留言 (遞迴查詢或 Closure Table)
- 圖片上傳 (整合 Intervention Image)
- 訂閱通知 (Email/Line/Telegram Bot)
- 管理後台 (刪除、編輯、置頂、封鎖)
- API 版本支援 SPA/行動應用