ThinkPHP 插入資料時,單雙引號自動被加上反斜線(hds"gh"j'g'h → hds\"gh\"j\'g\'h)。需徹底禁用此自動轉義,而非事後用 stripslashes() 清理。
雙重轉義導致:
magic_quotes_gpc = On 自動轉義 $_GET/POST/COOKIEescapeString() 再次轉義<?php
// 檔案:ThinkPHP/Lib/Driver/Db/DbMysql.class.php
public function escapeString($str) {
// 判斷 magic_quotes_gpc 是否已開啟
if (!get_magic_quotes_gpc()) {
if ($this->_linkID) {
return mysql_real_escape_string($str, $this->_linkID);
} else {
return mysql_escape_string($str);
}
} else {
// 已由 PHP 層轉義,直接返回原值,避免雙重轉義
return $str;
}
}
<?php
// 專案公共檔案(如 Common/common.php 或入口 index.php 最頂部)
if (get_magic_quotes_gpc()) {
function stripslashes_deep($value) {
$value = is_array($value)
? array_map('stripslashes_deep', $value)
: stripslashes($value);
return $value;
}
$_POST = array_map('stripslashes_deep', $_POST);
$_GET = array_map('stripslashes_deep', $_GET);
$_COOKIE = array_map('stripslashes_deep', $_COOKIE);
}
徹底理解轉義機制,才能從根源上解決資料「長刺」問題。