前端以 JSON 格式批量提交資料(如 [{'a':1},{'b':2}]),PHP 接收後卻變成 [{\'a\':1},{\'b\':2}],導致 json_decode 失敗。根因在於 PHP 設定 magic_quotes_gpc = On 自動對 $_POST 轉義單引號。
$json = $_POST['content']; // 接收原始字串
if (get_magic_quotes_gpc()) {
$json = stripslashes($json); // 移除自動加入的反斜線
}
$data = json_decode($json, true); // 正常解析為陣列
magic_quotes_gpc 為舊版 PHP(<5.4)預設開啟,會對 GET/POST/COOKIE 單引號、雙引號、反斜線、NULL 字元自動加反斜線。magic_quotes 轉義後變成 \',導致非合法 JSON。stripslashes() 可移除這層轉義,還原原始 JSON 字串。JSON.stringify() 產生標準雙引號 JSON,避免手拼字串。php.ini 設定 magic_quotes_gpc = Off(PHP 5.4+ 已移除此指令)。get_magic_quotes_gpc() 再決定是否 stripslashes,確保新舊環境皆正常。PHP 5.4 起 magic_quotes_gpc 已被移除,若仍遇到轉義問題,請檢查 Web 伺服器(如 Nginx/Apache 模組)或框架中間件是否有額外轉義邏輯。