需要完整原始 POST 数据时,使用 file_get_contents('php://input');处理表单提交时,使用 $_POST。两者不可混用,且 php://input 只能读取一次。

$_POST 与 php://input 的核心差异
$_POST 是 PHP 的超级全局数组,仅解析 application/x-www-form-urlencoded 或 multipart/form-data 格式的数据,并将其转换为键值对结构。而 php://input 是一个只读流,允许直接读取请求报文中原始的 POST 数据体,适用于 JSON、XML 或非标准编码格式。

当 Content-Type 为 application/x-www-form-urlencoded 时,PHP 会自动将数据填充到 $_POST 中,此时 php://input 的内容等同于未解析前的查询字符串。若 Content-Type 为 application/json,$_POST 将为空数组,必须通过 php://input 获取原始 JSON 字符串并解码。php://input 不支持 multipart/form-data 类型,因为该类型包含边界符和文件二进制流,无法简单作为文本流读取。
完整示例:兼容多种 POST 数据格式
以下代码演示如何根据 Content-Type 自动选择正确的数据获取方式,确保能处理表单、JSON 和 XML 请求。将代码保存为 index.php 并在本地服务器运行。

<?php
// 获取原始 POST 数据
$rawInput = file_get_contents('php://input');
// 初始化结果数组
$result = [
'raw' => $rawInput,
'type' => $_SERVER['CONTENT_TYPE'] ?? 'unknown',
'parsed' => null
];
// 如果 $_POST 为空,尝试解析原始数据
if (empty($_POST) && !empty($rawInput)) {
$contentType = $result['type'];
if (strpos($contentType, 'application/json') !== false) {
// 解析 JSON 数据
$decoded = json_decode($rawInput, true);
$result['parsed'] = $decoded;
} elseif (strpos($contentType, 'application/xml') !== false) {
// 解析 XML 数据(简化示例)
$xml = simplexml_load_string($rawInput);
$result['parsed'] = $xml ? json_decode(json_encode($xml), true) : null;
} else {
// 假设为 form-urlencoded,手动解析
parse_str($rawInput, $parsedArray);
$result['parsed'] = $parsedArray;
}
} else {
// 直接使用 $_POST
$result['parsed'] = $_POST;
}
// 输出结果用于调试
header('Content-Type: application/json');
echo json_encode($result, JSON_PRETTY_PRINT);
?>
发送 application/json 请求时,$_POST 为空,程序通过 php://input 获取 JSON 字符串并解码,最终输出解析后的关联数组。若发送 application/x-www-form-urlencoded 请求,$_POST 包含数据,程序直接使用它。注意:php://input 只能读取一次,因此必须先存储到变量 $rawInput 中。若重复调用 file_get_contents('php://input'),后续调用将返回空值。
程序先检查 $_POST 是否为空,若为空则尝试从 php://input 读取原始数据。随后根据 Content-Type 头判断数据格式,分别进行解析或保留原始字符串。接着输出解析后的数据结构,便于调试和后续业务逻辑处理。
php://input 读取失败与重复访问问题
如果在同一脚本中多次调用 file_get_contents('php://input'),第二次及之后的调用将返回空字符串,因为该流是单向且不可重置的。若请求体过大或客户端中断连接,可能导致读取不完整。
为避免重复读取问题,应在获取后将其存储在变量中供后续使用。对于大体积请求,建议配置 post_max_size 限制请求大小,防止内存溢出。在微服务架构中,网关层通常已解析 JSON 并转发至后端,此时后端可能直接接收 application/json 格式的原始数据,需确保应用层正确处理流式输入。