表單是 Web 互動的核心入口。PHP 透過超全域變數 $_GET、$_POST、$_REQUEST 輕鬆存取用戶提交的資料,但安全處理才是重中之重。
<!-- HTML 表單 -->
<form action="process.php" method="post">
<label>姓名: <input type="text" name="username"></label>
<label>Email: <input type="email" name="email"></label>
<button type="submit">送出</button>
</form>
<?php
// process.php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// 1. 取得並清理輸入
$username = trim($_POST['username'] ?? '');
$email = trim($_POST['email'] ?? '');
// 2. 基本驗證
$errors = [];
if ($username === '') $errors[] = '姓名不可為空';
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) $errors[] = 'Email 格式錯誤';
// 3. 處理結果
if (empty($errors)) {
// 安全處理:資料庫寫入、發送郵件等
echo "感謝 $username 註冊!";
} else {
echo "錯誤: " . implode(', ', $errors);
}
}
?>
| 威脅 | 防禦措施 |
|---|---|
| XSS (跨站腳本) | 輸出時用 htmlspecialchars($str, ENT_QUOTES, 'UTF-8') |
| SQL 注入 | 使用 PDO 預處理語句 $stmt->execute([$param]) |
| CSRF (跨站請求偽造) | 表單加入 CSRF Token 驗證 |
| 檔案上傳攻擊 | 驗證 MIME、副檔名、重新命名、存放非公開目錄 |