| 函數 | 功能 | 處理字符 | 典型場景 |
|---|---|---|---|
addslashes() | 在預定義字符前加反斜線 | 單引號 '、雙引號 "、反斜線 \、NULL 字節 | SQL 字串拼接(不推薦)、舊版相容 |
stripslashes() | 移除 addslashes() 加入的反斜線 | 連續兩個反斜線 → 一個;單一反斜線 → 移除 | 清理資料庫/表單取回的已轉義資料 |
<?php
$str = "Who's John Adams?";
// addslashes
$escaped = addslashes($str);
echo $escaped; // Who\'s John Adams?
// stripslashes
$original = stripslashes($escaped);
echo $original; // Who's John Adams?
// 連續反斜線行為
echo stripslashes('\\\\'); // \\ (兩個變一個)
echo stripslashes('\\'); // (空字串,單一反斜線被移除)
?>
舊版 PHP 預設開啟 magic_quotes_gpc = On,自動對 $_GET、$_POST、$_COOKIE 執行 addslashes()。導致:
addslashes())<?php
// 檢查是否已自動轉義
if (get_magic_quotes_gpc()) {
// 遞迴清理超全域陣列
function stripSlashesDeep(&$value) {
$value = is_array($value)
? array_map('stripSlashesDeep', $value)
: stripslashes($value);
return $value;
}
$_GET = stripSlashesDeep($_GET);
$_POST = stripSlashesDeep($_POST);
$_COOKIE = stripSlashesDeep($_COOKIE);
$_REQUEST = stripSlashesDeep($_REQUEST);
}
// 現代 PHP(5.4+)無需此步驟,magic_quotes_gpc 已移除
0xbf27 等字節序列會被誤判為單引號,繞過轉義%_ 等 LIKE 通配符、註釋符號 --、/*<?php
// PDO(推薦)
$pdo = new PDO('mysql:host=localhost;dbname=test;charset=utf8mb4', 'user', 'pass');
$stmt = $pdo->prepare('SELECT * FROM users WHERE email = ? AND status = ?');
$stmt->execute([$email, $status]);
$user = $stmt->fetch();
// MySQLi
$mysqli = new mysqli('localhost', 'user', 'pass', 'test');
$stmt = $mysqli->prepare('SELECT * FROM users WHERE email = ?');
$stmt->bind_param('s', $email);
$stmt->execute();
$result = $stmt->get_result();
預處理將 SQL 邏輯與資料分離,資料庫引擎保譯語句結構,資料永遠不會被解釋為 SQL 指令。
| 函數 | 用途 | 轉義字符 |
|---|---|---|
htmlspecialchars() | HTML 輸出防 XSS | & < > " ' |
htmlentities() | 所有 HTML 實體轉換 | 所有可轉換字符 |
json_encode() | JSON 字串化 | 控制字符、引號、反斜線、Unicode |
mysqli_real_escape_string() | MySQL 字串轉義(次佳) | NUL、\n、\r、\、'、"、\x1a |
addcslashes() | 自訂字符範圍轉義 | 指定範圍 |
<?php
/**
* 遞迴清理輸入資料(移除魔術引號殘留、修剪空白)
*/
function cleanInput(array &$data): void {
foreach ($data as $key => &$value) {
if (is_array($value)) {
cleanInput($value);
} else {
// 移除 magic_quotes 殘留(PHP 5.4+ 通常不需要)
if (get_magic_quotes_gpc()) {
$value = stripslashes($value);
}
// 修剪空白
$value = trim($value);
}
}
}
// 在入口檔案最早期呼叫
cleanInput($_GET);
cleanInput($_POST);
cleanInput($_COOKIE);
cleanInput($_REQUEST);
addslashes()/stripslashes() 是字串層面的簡單轉義/還原,不適合防 SQL 注入magic_quotes_gpc,新專案無需相容處理htmlspecialchars($str, ENT_QUOTES, 'UTF-8')json_encode()escapeshellarg()/escapeshellcmd()