萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 接收 POST 資料並解析 JSON 的正確姿勢

現代 API 開發中,Client 常以 `application/json` 格式發送資料,而非傳統 `application/x-www-form-urlencoded`。PHP 預設僅解析後者填入 `$_POST`,對於 JSON 請求需手動讀取輸入流並解碼。本文說明正確處理流程與常見坑點。

核心差異

Content-TypePHP 自動解析讀取方式
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]);

常見錯誤與修正

❌ 錯誤:直接用 `$_POST['json']`

$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()]));
}

進階:支援多種 Content-Type 的統一入口

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 限制),若需多次使用請先存入變數。
  • `json_decode($str, true)` 回傳關聯陣列;預設 `false` 回傳 `stdClass` 物件。
  • 大型 JSON(> 幾 MB)建議用流式解析(`JsonMachine` 等庫)避免記憶體耗盡。
  • 嚴格驗證 JSON 結構:搭配 `json_schema` 或自訂驗證類別。

掌握 `php://input` + `json_decode` 模式,是現代 PHP API 開發的基本功。

copyright © 萬盛學電腦網 all rights reserved