首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

PHP 多維陣列遞歸轉義實作:addslashes 深度遍歷完整指南

     編輯:PHP 綜合知識

核心函式實作

 &$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 注入風險,避免手動轉義的維護負擔與效能損耗。若必須維護舊代碼,請封裝為工具函式並加上單元測試覆蓋邊界情況 (空字串、巢狀深度、循環引用、物件屬性)。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved