
本文详解如何通过设置正确的 content-type 请求头,并配合 php 的 php://input 流,成功读取前端发送的原始 json 数据(如数字、对象等),避免因请求头缺失导致 file_get_contents('php://input') 返回空值的问题。
本文详解如何通过设置正确的 content-type 请求头,并配合 php 的 php://input 流,成功读取前端发送的原始 json 数据(如数字、对象等),避免因请求头缺失导致 file_get_contents('php://input') 返回空值的问题。
在使用 Angular 或其他前端框架向 PHP 后端发送原始数据(如纯数字、JSON 字符串)时,若未显式指定请求头,浏览器默认以 application/x-www-form-urlencoded 或 text/plain 发送,此时 PHP 不会将数据写入 php://input 流,导致 file_get_contents('php://input') 返回空字符串——这正是你看到 id:(后面仅为空格)的根本原因。
✅ 正确做法是:前端必须设置 Content-Type: application/json,确保服务器识别并接收原始请求体。
前端示例(Angular HttpClient)
import { HttpHeaders } from '@angular/common/http';
getOrdersByUser(user: number) {
const headers = new HttpHeaders().set('Content-Type', 'application/json');
return this.http.post('http://localhost/filename.php', user, { headers });
}⚠️ 注意:
user是一个数字(如4),Angular 会自动将其序列化为 JSON 字符串(即"4"),后端才能正确解析。
后端 PHP 完整处理逻辑
<?php
header('Content-Type: application/json; charset=utf-8');
// 读取原始请求体(仅当 Content-Type 为 application/json 时有效)
$rawInput = file_get_contents('php://input');
// 空输入保护
if (empty($rawInput)) {
http_response_code(400);
echo json_encode(['error' => 'No raw data received. Check Content-Type header.']);
exit;
}
// 解析 JSON —— 支持数字、字符串、对象、数组
$id = json_decode($rawInput, true);
// 验证解析结果
if (json_last_error() !== JSON_ERROR_NONE) {
http_response_code(400);
echo json_encode(['error' => 'Invalid JSON format.', 'raw' => $rawInput]);
exit;
}
// 成功获取 ID(可能是 int、string 或 null)
echo json_encode(['success' => true, 'received_id' => $id]);
?>关键要点总结:
- ❌ 错误:直接发送数字(如
3)却不设Content-Type: application/json→ PHP 无法识别为 JSON,php://input为空; - ✅ 正确:前端显式设置
Content-Type: application/json,即使发送纯数字,也会被序列化为合法 JSON; - ? 调试建议:在 PHP 中先
var_dump($rawInput)和var_dump(json_last_error()),快速定位是传输问题还是解析问题; - ? 补充说明:
$_POST仅对x-www-form-urlencoded或multipart/form-data有效,绝不可用于读取php://input内容。
遵循以上规范,即可稳定、可靠地实现前端原始数据(含数字、JSON 对象等)到 PHP 后端的传递与解析。
立即学习“PHP免费学习笔记(深入)”;



















