早期 PHP 專案常在通用引入檔包含清洗類,自動處理 $_GET/$_POST 過濾 SQL 注入、XSS 字元。現代框架已內建更完善機制,但理解原理有助於維護舊專案。
<?php
class StrSwap {
var $GetSplitStr = "&&"; // GET 參數分隔符(非標準,標準為 &)
var $TempArray = array();
var $VariableArray = array();
// 主入口:自動偵測 GET/POST
function Main() {
global $REQUEST_METHOD;
if ("GET" == $REQUEST_METHOD) {
$this->SubGetStrToArray();
}
if ("POST" == $REQUEST_METHOD) {
$this->SubPostStrToArray();
}
$this->GlobalVariable();
}
// GET 字串解析
function SubGetStrToArray() {
global $QUERY_STRING;
$this->TempArray = explode($this->GetSplitStr, $QUERY_STRING);
for ($i = 0; $i < sizeof($this->TempArray); $i++) {
$temp = explode('=', $this->TempArray[$i]);
$this->VariableArray[$i][0] = $temp[0];
$this->VariableArray[$i][1] = $this->StrReplace($temp[1]);
}
}
// POST 資料處理(原碼未完整,補全邏輯)
function SubPostStrToArray() {
foreach ($_POST as $key => $val) {
$this->VariableArray[] = array($key, $this->StrReplace($val));
}
}
// 註冊為全域變數(模擬 register_globals)
function GlobalVariable() {
foreach ($this->VariableArray as $pair) {
$GLOBALS[$pair[0]] = $pair[1];
// 或 ${$pair[0]} = $pair[1];
}
}
// 核心過濾函數
function StrReplace($str) {
// 防 SQL 注入
$str = str_replace("'", "''", $str); // 單引號轉義
$str = str_replace('"', '\"', $str); // 雙引號轉義
$str = str_replace(';', '', $str); // 移除分號
$str = str_replace('--', '', $str); // 移除 SQL 註釋
$str = str_replace('/*', '', $str); // 移除 SQL 註釋開始
$str = str_replace('*/', '', $str); // 移除 SQL 註釋結束
// 防 XSS
$str = str_replace('<', '<', $str);
$str = str_replace('>', '>', $str);
$str = str_replace('(', '(', $str);
$str = str_replace(')', ')', $str);
return $str;
}
}
// 自動執行
$strSwap = new StrSwap();
$strSwap->Main();
?>
| 問題 | 影響 | 現代替代方案 |
|---|---|---|
| 黑名單過濾 | 繞過手法無窮(編碼、大小寫、註釋變形) | 參數化查詢 / 預處理語句 |
| GET 分隔符錯誤 | && 非標準,實際為 & | 直接用 $_GET 陣列 |
| 雙重編碼風險 | 多次 include 導致重複轉義 | 輸出時轉義,輸入不轉義 |
| 破壞合法資料 | 如姓名 O'Brien 變 O''Brien | 參數化查詢保留原始資料 |
| 註冊全域變數 | 汙染全域命名空間、變數覆蓋風險 | 直接使用 $_GET/$_POST |
| 缺少遞迴處理陣列輸入 | name[]=a&name[]=b 會失效 | 遞迴 filter_var_array() |
filter_input_array()、filter_var_array() 驗證型別、範圍、格式htmlspecialchars() (HTML)、json_encode() (JS)、urlencode() (URL)StrSwap 引用點$_GET/$_POST 直接存取htmlspecialchars()StrSwap 類別與自動執行代碼