基本處理流程
$input = $_POST['user_input'] ?? '';
// 1. 去除首尾空白
$input = trim($input);
// 2. 移除 HTML/PHP 標籤
$input = strip_tags($input);
// 允許特定標籤:strip_tags($input, '')
// 3. HTML 實體編碼 (輸出至頁面前)
$safeHtml = htmlspecialchars($input, ENT_QUOTES, 'UTF-8');
// 4. 資料庫存儲:使用預處理語句,無需 addslashes
// $stmt = $pdo->prepare("INSERT INTO t (c) VALUES (?)");
// $stmt->execute([$input]); // 直接傳入原始字串
// 5. 若需用於 SQL 字串拼接 (不推薦):
$escaped = $pdo->quote($input); // 含引號
// 或 mysqli_real_escape_string($link, $input)
函式用途對照
| 函式 | 用途 | 是否資料庫安全 |
trim() | 移除首尾空白/換行 | 否 |
strip_tags() | 剝離 HTML/PHP 標籤 | 否 |
htmlspecialchars() | 編碼 <>&"' 為實體 | 否 (僅防 XSS) |
htmlentities() | 編碼所有適用字元 | 否 |
addslashes() | 引號前加反斜線 | 不完全 (視字元集/驅動) |
mysqli_real_escape_string() | 依連線字元集跳脫 | 僅限 mysqli、非預處理 |
PDO::quote() | 依驅動跳脫並加引號 | 僅限 PDO、非預處理 |
| 預處理語句 | 參數綁定,資料與指令分離 | 是 (最佳) |
完整表單範例
prepare("INSERT INTO contacts (name, email, message, created_at) VALUES (?, ?, ?, NOW())");
$stmt->execute([$name, $email, $message]);
header('Location: thanks.php');
exit;
}
}
?>
進階建議
- 使用
filter_var()、filter_input() 進行驗證/過濾 (Email、URL、IP、Int、Regex)。
- 引入驗證庫:
symfony/validator、respect/validation。
- 內容安全政策 (CSP) 標頭防禦 XSS:
Content-Security-Policy: default-src 'self'; script-src 'self'。
- 檔案上傳:驗證 MIME、副檔名、大小,重命名儲存,禁止直接執行。