早期 PHP 有 magic_quotes_gpc 自動轉義功能,現已棄用/移除。本文提供一個函數 my_addslashes() 封裝邏輯:自動檢測 magic_quotes_gpc 狀態,對 $_GET、$POST、$_COOKIE 所有值遞迴執行 addslashes(),並將變數直接註冊到當前符號表 (如 $var),方便直接使用。
<?php
function my_addslashes($string, $force = 0) {
!defined('MAGIC_QUOTES_GPC') && define('MAGIC_QUOTES_GPC', get_magic_quotes_gpc());
if (!MAGIC_QUOTES_GPC || $force) {
if (is_array($string)) {
foreach ($string as $key => $val) {
$string[$key] = my_addslashes($val, $force);
}
} else {
$string = addslashes($string);
}
}
return $string;
}
// 遍歷三大超全域陣列,將值轉義後以變數名直接可用 (如 $username)
foreach (array('_COOKIE', '_POST', '_GET') as $_request) {
foreach ($$_request as $_key => $_value) {
if ($_key[0] != '_') { // 略過以底線開頭的鍵 (視需求)
$$_key = my_addslashes($_value);
}
}
}
// 現在可直接使用 $urls (對應 $_GET['urls'] 或 $_POST['urls'] 等)
echo $urls;
?>
get_magic_quotes_gpc() 檢查舊版自動轉義是否開啟;若已開啟則不重複轉義 (除非 $force=1)。is_array() 遞迴處理陣列值 (如 name[]=a&name[]=b)。addslashes() 在單引號、雙引號、反斜線、NULL 前加反斜線。$$_key (Variable variables) 將陣列鍵值轉為同名變數 (例:$_GET['id'] → $id)。addslashes() 無法防禦 SQL 注入,資料庫操作請務必使用 Prepared Statements (PDO/MySQLi)。magic_quotes_gpc (PHP 5.4+ 已移除)。filter_var()、htmlspecialchars() (輸出時)。htmlspecialchars($str, ENT_QUOTES, 'UTF-8')。json_encode()。<?php
// 取得 GET 參數,預設空字串,並去除首尾空白
$id = trim($_GET['id'] ?? '');
// 取得 POST 陣列,預設空陣列
$tags = $_POST['tags'] ?? [];
// 統一過濾函數 (僅示範,實務視情境)
function clean_input($data) {
if (is_array($data)) return array_map('clean_input', $data);
return htmlspecialchars(trim($data), ENT_QUOTES, 'UTF-8');
}
?>