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

ThinkPHP 表單提交自動轉義問題徹底解決方案

     編輯:PHP 綜合知識

問題現象

ThinkPHP 插入資料時,單雙引號自動被加上反斜線(hds"gh"j'g'h → hds\"gh\"j\'g\'h)。需徹底禁用此自動轉義,而非事後用 stripslashes() 清理。

根因分析

雙重轉義導致:

  1. PHP 設定 magic_quotes_gpc = On 自動轉義 $_GET/POST/COOKIE
  2. ThinkPHP 資料庫驅動 escapeString() 再次轉義
  3. 結果:資料庫存入雙重轉義字串

方案一:修改資料庫驅動層(治本)

<?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);
}

現代 PHP 環境建議

  • PHP 5.4+ 已移除 magic_quotes_gpc,新專案不會遇此問題
  • 舊專案升級時,建議採用方案二,不侵入框架核心
  • 資料庫操作統一使用參數綁定(Prepared Statements),完全避開轉義問題

徹底理解轉義機制,才能從根源上解決資料「長刺」問題。

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