如何在 PHP 中正确获取 POST 请求的请求头信息(含查询参数)

本文详解如何通过 PHP 原生方式(file_get_contents + stream_context_create)发送带表单数据的 POST 请求,并在服务端准确捕获完整的 HTTP 请求头及原始请求体,避免误用 exec(curl) 导致的上下文丢失与安全风险。

本文详解如何通过 PHP 原生方式(`file_get_contents` + `stream_context_create`)发送带表单数据的 POST 请求,并在服务端准确捕获完整的 HTTP 请求头及原始请求体,避免误用 `exec(curl)` 导致的上下文丢失与安全风险。

在 PHP 中调试 POST 请求时,一个常见误区是混淆「请求头(Request Headers)」与「请求体(Request Body)」——你当前代码中试图通过 apache_request_headers() 打印客户端发送的 Header,但实际期望看到的是提交的表单参数(如 feed_them_social=yes),而这些参数默认不会出现在 HTTP 头部中,而是以 application/x-www-form-urlencoded 格式编码后置于请求体(content)内。

你原代码的问题核心在于:

✅ 推荐修正方案(客户端):

$postdata = http_build_query([
    'feed_them_social' => 'yes',
    'refresh_token'    => get_option('custom_refresh_token'),
    'time'             => esc_html(get_option('custom_token_exp_time')),
]);

$opts = [
    'http' => [
        'method'  => 'POST',
        'header'  => "Content-type: application/x-www-form-urlencoded\r\n" .
                     "Content-Length: " . strlen($postdata) . "\r\n",
        'content' => $postdata,
    ]
];

$context = stream_context_create($opts);
$response = file_get_contents('https://my-url.com', false, $context);

if ($response === false) {
    throw new Exception('HTTP request failed: ' . error_get_last()['message']);
}

echo '<pre>'; print_r($response); echo '</pre>';

⚠️ 注意事项:

? 总结:不要用 exec(curl) 拼接上下文;优先使用 file_get_contents() 配合 stream_context_create() 实现安全、可控的 HTTP 请求;服务端获取参数应依赖 $_POST(表单提交)或 php://input(原始体),而非误读请求头。

本文转载于:互联网 如有侵犯,请联系zhengruancom@outlook.com删除。
免责声明:正软商城发布此文仅为传递信息,不代表正软商城认同其观点或证实其描述。