前端傳送標準 JSON:[{"a":1,"b":"test"}]
PHP 接收到:[{"a":1,"b":"test"}](單引號被跳脫為 \')
導致 json_decode() 失敗或解析錯誤。
PHP 設定 magic_quotes_gpc = On(PHP 5.4 前預設開啟),自動對 $_GET、$_POST、$_COOKIE 執行 addslashes()。
此特性已於 PHP 5.4 移除,但舊環境或特定主機可能仍啟用。
$json = $_POST['content']; // 或 file_get_contents('php://input')
// 相容處理:檢測並移除魔術引號
if (get_magic_quotes_gpc()) {
$json = stripslashes($json);
}
$data = json_decode($json, true); // 解析為關聯陣列
if (json_last_error() !== JSON_ERROR_NONE) {
// 處理解析錯誤
throw new Exception('JSON 格式錯誤: ' . json_last_error_msg());
}
// 直接讀取原始輸入流,繞過 $_POST 自動解析與 magic_quotes
$json = file_get_contents('php://input');
$data = json_decode($json, true);
php://input 取得原始 POST 資料,不受 magic_quotes_gpc 影響multipart/form-data(檔案上傳),僅適用 application/json、text/plain$GLOBALS['HTTP_RAW_POST_DATA'](已棄用)// jQuery
$.ajax({
url: '/api/endpoint',
method: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify([{a:1,b:'test'}]),
success: function(res) { ... }
});
// 原生 fetch
fetch('/api/endpoint', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify([{a:1,b:'test'}])
});
magic_quotes_gpc 困擾file_get_contents('php://input') 接收 JSON
3. 前端設定 Content-Type: application/json
4. 解析後檢查 json_last_error(),提供明確錯誤回饋
5. 若必須相容舊環境,保留 get_magic_quotes_gpc() + stripslashes() 防禦性編碼