萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 反斜線處理函數 addslashes() 與 stripslashes() 完整教學

函數用途對比

函數功能處理字符典型場景
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('\\');   // (空字串,單一反斜線被移除)
?>

magic_quotes_gpc 歷史遺留問題(PHP 5.4 已移除)

舊版 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 已移除

為什麼不建議用 addslashes() 防 SQL 注入?

  1. 字元集問題:GBK/Big5 多位元組編碼下,0xbf27 等字節序列會被誤判為單引號,繞過轉義
  2. 不完整覆蓋:未處理 %_ 等 LIKE 通配符、註釋符號 --、/*
  3. 無法防禦二次注入:資料存入後再次查詢拼接時保護失效

正確防禦 SQL 注入:預處理語句

<?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 注入
  • PHP 5.4+ 已移除 magic_quotes_gpc,新專案無需相容處理
  • 資料庫操作必須使用預處理語句
  • HTML 輸出使用 htmlspecialchars($str, ENT_QUOTES, 'UTF-8')
  • JSON 輸出使用 json_encode()
  • Shell 指令參數使用 escapeshellarg()/escapeshellcmd()
  • 針對不同輸出語境使用對應的轉義函數,是安全開發的核心原則
copyright © 萬盛學電腦網 all rights reserved