現代 API 開發中,Client 常以 `application/json` 格式發送資料,而非傳統 `application/x-www-form-urlencoded`。PHP 預設僅解析後者填入 `$_POST`,對於 JSON 請求需手動讀取輸入流並解碼。本文說明正確處理流程與常見坑點。
| Content-Type | PHP 自動解析 | 讀取方式 |
|---|---|---|
| application/x-www-form-urlencoded | 是 → `$_POST` | `$_POST['key']` |
| multipart/form-data | 是 → `$_POST` / `$_FILES` | `$_POST['key']` / `$_FILES['file']` |
| application/json | 否 | `file_get_contents('php://input')` + `json_decode()` |
<?php
// 1. 讀取原始輸入流
$jsonString = file_get_contents('php://input');
// 2. 處理 magic_quotes_gpc 歷史遺留問題(PHP 5.4+ 已移除,保留相容性)
if (function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc()) {
$jsonString = stripslashes($jsonString);
}
// 3. 解碼 JSON
$data = json_decode($jsonString, true); // true = 回傳關聯陣列
// 4. 錯誤檢查
if (json_last_error() !== JSON_ERROR_NONE) {
http_response_code(400);
exit(json_encode(['error' => 'Invalid JSON: ' . json_last_error_msg()]));
}
// 5. 後續業務邏輯使用 $data
// $userId = $data['user_id'] ?? null;
// ...
echo json_encode(['status' => 'ok', 'received' => $data]);
$json_string = $_POST["txt_json"]; // 只有在 Content-Type 為 form 且欄位名為 txt_json 才有值
若 Client 送 `Content-Type: application/json`,`$_POST` 為空陣列。
function getJsonInput() {
$input = file_get_contents('php://input');
if (function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc()) {
$input = stripslashes($input);
}
$data = json_decode($input, true);
if (json_last_error() !== JSON_ERROR_NONE) {
throw new InvalidArgumentException('Invalid JSON: ' . json_last_error_msg());
}
return $data;
}
// 使用
try {
$data = getJsonInput();
} catch (InvalidArgumentException $e) {
http_response_code(400);
exit(json_encode(['error' => $e->getMessage()]));
}
function getRequestData() {
$contentType = $_SERVER['CONTENT_TYPE'] ?? '';
if (strpos($contentType, 'application/json') === 0) {
return getJsonInput();
}
// multipart/form-data 或 application/x-www-form-urlencoded
return $_POST; // 已自動解析
}
# 正確的 JSON 請求
curl -X POST https://localhost/api.php \
-H "Content-Type: application/json" \
-d '{"name":"John","age":30}'
# 錯誤:表單格式卻送 JSON 內容
curl -X POST https://localhost/api.php \
-d '{"name":"John"}' # 缺少 Content-Type,PHP 視為表單,$_POST 會有鍵 '{"name":"John"}'
php://input 只能讀取一次(部分 SAPI 限制),若需多次使用請先存入變數。掌握 `php://input` + `json_decode` 模式,是現代 PHP API 開發的基本功。