我正在尝试使用PHP的stream_get_contents
机制发出请求,因为我没有CURL。此请求在本地工作正常但在部署到远程服务器时不会发送所有标头。这是PHP片段:
<?php
$context = stream_context_create(array(
'http' => array(
'method' => 'POST',
'header' => array(
'Content-type: application/json',
'Authorization: Basic '.base64_encode('username:secret'),
),
'content' => json_encode(array(
'key' => 'value',
)),
)
));
file_get_contents('http://requestb.in/xxxxxx', false, $context);
?>
当从本地计算机执行此操作时,我看到服务器收到以下标题:
Via: 1.1 vegur
Authorization: Basic dXNlcm5hbWU6c2VjcmV0
Host: requestb.in
Content-Length: 70
Total-Route-Time: 0
Content-Type: application/json
X-Request-Id: a2cf10d8-a82a-4302-897f-3f40daa22028
Connect-Time: 1
Connection: close
...这就是我从远程服务器执行代码片段时得到的内容。
User-Agent: PHP/5.2.17
Host: requestb.in
Via: 1.1 vegur
X-Request-Id: 14e7af5f-39aa-474a-8d1a-af992997d0ef
Content-Length: 70
Total-Route-Time: 0
Content-Type: application/x-www-form-urlencoded
Accept: */*
Connect-Time: 7
Connection: close
内容长度不同,因为我已经修改了我的pOST请求的有效负载,但正如您所看到的,我无法在第二种情况下获得Authorisation
标头并且Content-Type
标头已更改太
我真的迷失了这个,并没有找到这种古怪行为的解释。 (我正在使用RequestBin来帮助我解决问题。)
答案 0 :(得分:1)
如果使用flag&#34; - with-curlwrappers&#34;编译php,则此问题可能是由于php中的错误引起的。 https://bugs.php.net/bug.php?id=55438
答案 1 :(得分:0)
上下文数组中的'header'
键必须是字符串。请参阅PHP docs here
$method = 'GET';
$contextOptions = array(
'http' => array(
'method' => $method,
'header' => array(
'X-Forwarded-For: ' . $_SERVER['REMOTE_ADDR'],
'Authorization: Basic ' . base64_encode($apiKey . ':' . $flags),
),
)
);
if ('POST' === $method || 'GET' === $method) {
$contextOptions['http']['header'][] = 'Content-Type: application/x-www-form-urlencoded';
} elseif ('PUT' === $method || 'UPDATE' === $method) {
$contextOptions['http']['header'][] = 'Content-Type: application/octet-stream';
}
$contextOptions['http']['header'][] = 'Content-Length: ' . strlen($data);
$contextOptions['http']['content'] = $data;
$contextOptions['http']['header'] = implode("\r\n", $contextOptions['http']['header']);
答案 2 :(得分:0)
主要问题是Authorization标头丢失了吗?我有类似的问题通过编辑.htaccess文件解决,如下所示:
RewriteEngine on
RewriteCond %{HTTP:Authorization} ^(.)
RewriteRule . - [e=HTTP_AUTHORIZATION:%1]