&$value) {
recursiveAddslashes($value); // 引用傳遞,直接修改原陣列
}
} elseif (is_string($data)) {
$data = addslashes($data);
}
// 數值、布林、null、物件保持不變
}
// 使用範例
$arr = [
"name" => "O'Reilly",
"tags" => ["PHP", "MySQL", "O'Reilly"],
"nested" => [
"bio" => "It's a \"test\"",
"empty" => "",
],
"number" => 123,
"bool" => true,
];
recursiveAddslashes($arr);
print_r($arr);
/*
Array
(
[name] => O\'Reilly
[tags] => Array
(
[0] => PHP
[1] => MySQL
[2] => O\'Reilly
)
[nested] => Array
(
[bio] => It\'s a \"test\"
[empty] =>
)
[number] => 123
[bool] => 1
)
*/
?>
&$value) {
recursiveAddslashesDeep($value, $visited);
}
} elseif (is_object($data)) {
foreach ($data as $key => &$value) {
recursiveAddslashesDeep($value, $visited);
}
} elseif (is_string($data)) {
$data = addslashes($data);
}
}
?>
&$value) {
if (is_array($value)) {
$stack[] = &$value;
} elseif (is_string($value)) {
$value = addslashes($value);
}
}
}
}
?>
prepare("INSERT INTO articles (title, content) VALUES (?, ?)");
$stmt->execute([$title, $content]); // 自動處理引號、編碼
// mysqli 預處理
$stmt = $mysqli->prepare("INSERT INTO articles (title, content) VALUES (?, ?)");
$stmt->bind_param('ss', $title, $content);
$stmt->execute();
?>
| 場景 | 是否適用 | 說明 |
|---|---|---|
| 老專案字串拼接 SQL | ✅ 必須 | 配合 magic_quotes_gpc 關閉 |
| JSON API 輸出 | ❌ 禁止 | json_encode 自動處理,addslashes 會產生雙重轉義 |
| HTML 輸出 | ❌ 禁止 | 用 htmlspecialchars,非 addslashes |
| Shell 命令參數 | ⚠️ 慎用 | 用 escapeshellarg/escapeshellcmd |
| 資料庫備份/匯出 SQL 檔 | ✅ 適用 | 手動構建 INSERT 語句時 |
遞歸 addslashes 核心模式:**引用傳遞 + is_array 判斷 + 字串轉義**。現代專案**強烈建議全面改用預處理語句**,從根源消除 SQL 注入風險,避免手動轉義的維護負擔與效能損耗。若必須維護舊代碼,請封裝為工具函式並加上單元測試覆蓋邊界情況 (空字串、巢狀深度、循環引用、物件屬性)。