<?php
/**
* 遞迴處理陣列,移除魔術引號(舊版 PHP 遺留)並修剪空白
*/
function cleanInput($data) {
if (is_array($data)) {
return array_map('cleanInput', $data);
}
// PHP 5.4+ 已移除 magic_quotes_gpc,此判斷僅相容舊環境
if (get_magic_quotes_gpc()) {
$data = stripslashes($data);
}
return trim($data);
}
// 在程式入口統一處理
$_GET = cleanInput($_GET);
$_POST = cleanInput($_POST);
$_COOKIE = cleanInput($_COOKIE);
$_REQUEST = cleanInput($_REQUEST);
?>
<?php
/**
* 輸出到 HTML 內容區塊時使用
*/
function h($str, $encoding = 'UTF-8') {
return htmlspecialchars($str, ENT_QUOTES | ENT_SUBSTITUTE, $encoding);
}
/**
* 輸出到 HTML 屬性值時使用(雙引號包裹)
*/
function hAttr($str, $encoding = 'UTF-8') {
return htmlspecialchars($str, ENT_QUOTES | ENT_SUBSTITUTE, $encoding);
}
// 使用範例
echo '<div>' . h($userComment) . '</div>';
echo '<input value="' . hAttr($userInput) . '">';
<?php
$pdo = new PDO('mysql:host=localhost;dbname=test;charset=utf8mb4', 'user', 'pass');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $pdo->prepare('SELECT * FROM users WHERE email = ? AND status = ?');
$stmt->execute([$email, 1]);
$user = $stmt->fetch(); // 完全免疫 SQL 注入
嘗試用 str_replace 過濾 select、union、script 等關鍵字: