當 Content-Type 非 application/x-www-form-urlencoded 或 multipart/form-data (如 JSON、XML、原始文字) 時,$_POST 為空,需讀取 php://input 取得原始請求主體。
<form action="action.php" method="post">
<input type="text" name="userName" id="userName"><br/>
<input type="text" name="userPass" id="userPass"><br/>
<input type="submit" value="ok">
</form>
<?php
// action.php
$raw_post_data = file_get_contents('php://input');
echo "------- \$_POST ----------------<br/>";
var_dump($_POST);
echo "------- php://input ------------<br/>";
echo $raw_post_data . "<br/>";
?>
$_POST 含解析後陣列;php://input 為 userName=abc&userPass=123。Content-Type: application/json):$_POST 為空陣列;php://input 為 {"userName":"abc","userPass":"123"},需 json_decode($raw, true) 解析。php://input 只能讀取一次 (流不可重複讀取),需存變數復用。enable_post_data_reading = Off (php.ini) 可禁用自動填入 $_POST/$_FILES 節省記憶體,但需自行解析。<?php
header('Content-Type: application/json; charset=UTF-8');
$input = file_get_contents('php://input');
$data = json_decode($input, true);
if (json_last_error() !== JSON_ERROR_NONE) {
http_response_code(400);
exit(json_encode(['error' => 'Invalid JSON']));
}
// 业务逻辑...
echo json_encode(['status' => 'ok', 'received' => $data]);
?>