为什么我的授权标头在使用stream_get_contents时消失了


Why does my Authorisation header disappear when using stream_get_contents?

我正在尝试使用 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 来帮助我解决问题。

如果使用标志"--with-curlwrappers"编译php,那么这个问题可能是由于php中的错误造成的。https://bugs.php.net/bug.php?id=55438

上下文

数组中的'header'键必须是字符串。在此处查看 PHP 文档中的示例

$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']);

您的主要问题是缺少授权标头吗? 我有一个类似的问题,通过编辑.htaccess文件解决了,如下所示:


    RewriteEngine on
    RewriteCond %{HTTP:Authorization} ^(.)
    RewriteRule . - [e=HTTP_AUTHORIZATION:%1]