我有一个奇怪的卷曲问题。示例代码如下。当我运行它时,服务器不会收到$_SERVER
数组中的CUSTOM_HEADER
标头。如果我删除CURLOPT_POSTFIELDS
选项,则会出现标题。
看起来设置CURLOPT_POSTFIELDS
覆盖了CURLOPT_HTTPHEADER
中添加的标头(但我在任何地方都找不到记录)。这是对的吗?
更改顺序似乎并不重要。我也无法通过设置其他选项来修复它。
<?php
$url = 'http://whatever.url';
$text = 'The quick brown fox jumps over the lazy dog.';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('CUSTOM_HEADER: TEST HEADER VALUE'));
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(array('text' => $text)));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
var_dump($response);
我发布的脚本仅返回$_SERVER
信息:
<?php
echo json_encode($_SERVER);
die();
在$response
数组中,我得到很多请求标头,但没有CUSTOM_HEADER
.
是否有其他方法可以将POST
数据发送到请求中带有自定义标头的 URL?
curl 端工作正常,但要获取请求标头,您应该使用 getallheaders()。
如果发布到此脚本:
<?php echo json_encode( [
'headers' => getallheaders(),
'post' => $_POST
] );
并像这样打印$response
:
echo "<pre>" . print_r( json_decode( $response ), 1 ) . "</pre>";
它应该显示
stdClass Object
(
[headers] => stdClass Object
(
[Host] => whatever.url
[Accept] => */*
[CUSTOM_HEADER] => TEST HEADER VALUE
[Content-Length] => 49
[Content-Type] => application/x-www-form-urlencoded
)
[post] => stdClass Object
(
[text] => The quick brown fox jumps over the lazy dog.
)
)