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

PHP magic_quotes_gpc 對 unserialize 影響分析與解決方案

     編輯:PHP 相關知識

PHP magic_quotes_gpc 對 unserialize 影響分析與解決方案

背景:magic_quotes_gpc 自 PHP 5.4.0 起已移除。本文針對舊版 PHP(≤5.3)維護專案,分析其對序列化資料的影響及相容性處理。

問題現象

購物車資料序列化存入 Cookie,反序列化時失敗:

<?php
// 寫入 Cookie
$cart = [['goods_id' => 13, 'number' => 1]];
setcookie('cart', serialize($cart));

// 讀取並反序列化
$cart = unserialize($_COOKIE['cart']); // ⚠️ 可能失敗
?>

根本原因

當 magic_quotes_gpc = On 時,PHP 自動對 GET/POST/COOKIE 資料的單引號、雙引號、反斜線、NULL 字元加上反斜線跳脫。

序列化字串包含大量引號:

a:1:{i:0;a:2:{s:8:"goods_id";i:13;s:6:"number";i:1;}}

經跳脫後變為:

a:1:{i:0;a:2:{s:8:\"goods_id\";i:13;s:6:\"number\";i:1;}}

unserialize() 无法解析被跳脫的字串,導致回傳 false 或拋出錯誤。

解決方案

方法一:反序列化前移除跳脫(最直接)

<?php
$cart = unserialize(stripslashes($_COOKIE['cart']));
?>

方法二:統一處理 GPC 資料(框架/專案入口)

<?php
if (get_magic_quotes_gpc()) {
    function stripslashes_deep($value) {
        return is_array($value) ? array_map('stripslashes_deep', $value) : stripslashes($value);
    }
    $_GET    = stripslashes_deep($_GET);
    $_POST   = stripslashes_deep($_POST);
    $_COOKIE = stripslashes_deep($_COOKIE);
    $_REQUEST = stripslashes_deep($_REQUEST);
}
?>

JSON + Cookie 同樣受影響

<?php
$data = ['key' => '值'];
$json = json_encode($data);          // 正常
setcookie('test', $json);

// magic_quotes_gpc=On 時,$_COOKIE['test'] 會被加上反斜線
var_dump(json_decode($_COOKIE['test'], true)); // ❌ null

// 解決
var_dump(json_decode(stripslashes($_COOKIE['test']), true)); // ✅ 正常
?>

最佳實務總結

情境處理原則
magic_quotes_gpc = On讀取 GPC 資料前統一 stripslashes
magic_quotes_gpc = Off寫入資料庫/快取前自行 addslashes(或用 Prepared Statement),讀出後 stripslashes
現代 PHP(≥5.4)完全忽略,專注於 Prepared Statement 與 json_encode/decode

遷移建議

  • 升級 PHP ≥ 5.4,移除所有 get_magic_quotes_gpc() 判斷邏輯
  • 資料庫操作全面改用 PDO Prepared Statement
  • 序列化儲存優先使用 json_encode,避免 serialize 類別依賴與編碼問題
  • Cookie 儲存敏感資料請加密(如 openssl_encrypt)並簽名驗證

希望本文協助您解決舊專案的 magic_quotes_gpc 相容性問題。

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