
本文详解如何通过 PHP 原生方式(file_get_contents + stream_context_create)发送带表单数据的 POST 请求,并在服务端准确获取完整的请求头及原始请求体内容,避免误用 exec(curl) 导致的上下文丢失与安全风险。
本文详解如何通过 php 原生方式(`file_get_contents` + `stream_context_create`)发送带表单数据的 post 请求,并在服务端准确获取完整的请求头及原始请求体内容,避免误用 `exec(curl)` 导致的上下文丢失与安全风险。
在 PHP 中调试 POST 请求时,常见误区是混淆「请求头(Headers)」与「请求体(Body)」——你当前看到的 Content-Length、Content-Type 等属于服务器接收到的 HTTP 请求头,而你真正想获取的 'feed_them_social=yes&refresh_token=xxx&time=xxx' 这类键值对,实际位于请求体(Request Body)中,并非请求头的一部分。
你原代码中使用 exec('curl --data ...') 是根本性错误:$context 是一个资源句柄(resource),将其拼入字符串并执行 shell 命令不仅完全无效($context 不可直接转为 curl 参数),更存在严重命令注入风险和环境依赖问题(如未安装 curl、权限限制等)。
✅ 正确做法是使用 file_get_contents() 配合 stream_context_create() 发起请求,它能完整传递配置的 header 和 body:
$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 RuntimeException('HTTP request failed: ' . error_get_last()['message']);
}
echo '<pre class="brush:php;toolbar:false;">'; print_r($response); echo '';⚠️ 注意事项:
立即学习“PHP免费学习笔记(深入)”;
- 必须显式设置 Content-Length:虽然部分服务器可自动推断,但显式声明是 RFC 合规且兼容性更佳的做法;
- 换行符使用 \r\n:HTTP 头部字段分隔符为 CRLF,不可用 \n 替代;
- 服务端接收请求体:在目标 URL(如 https://my-url.com)的 PHP 脚本中,应使用 file_get_contents('php://input') 获取原始 POST 数据(而非 $_POST,因 $_POST 仅在 Content-Type 匹配且解析成功时填充):
// 在 https://my-url.com 对应的 PHP 文件中
$headers = apache_request_headers();
echo "<h3>Received Headers:</h3><pre class="brush:php;toolbar:false;">";
foreach ($headers as $key => $val) {
echo "$key: $val\n";
}
echo "";
echo "Raw POST Body:
";
$body = file_get_contents('php://input');
echo htmlspecialchars($body); // 安全输出,防 XSS
echo "";? 总结:
不要用 exec(curl) 模拟 HTTP 请求——它绕过 PHP 流上下文、无法传递 $context、易被注入、难调试;始终优先选用 file_get_contents() 或更现代的 cURL 扩展(curl_init())。同时明确区分:请求头(headers)由 apache_request_headers() 获取,请求体(body)需用 php://input 读取——二者协同,才能完整还原客户端发起的原始 POST 请求。



















