file_get_contents 不使用承载

file_get_contents not working with bearer

我一直收到这个错误

Warning: file_get_contents failed to open stream: HTTP request failed! HTTP/1.1 401 Unauthorized

代码

$url = BASE_URL . 'api/v1/users';
$options = array('http' => array(
    'method'  => 'GET',
    'header' => 'Authorization: Bearer '.$token
));
$context  = stream_context_create($options);
$response = file_get_contents($url, false, $context);

我在 api 中使用的中间件通过 url 参数或 header 接受授权;

如果我在参数中使用令牌,它可以工作但无法通过服务器上的 header 发送它,因为在本地主机上它可以工作,

请求是通过不记名令牌授权的我没有任何用户名和密码来授权请求​​,正如我在下面演示的那样我只在我的url参数中使用令牌。

知道为什么吗?如果不将所有请求更改为 curl

,我能做什么
$result = file_get_contents(BASE_URL . 'api/v1/users?authorization='.$token, false);
$response = json_decode($result, true);

您可以使用 CURL 进行请求

 $opts = array(
                'http'=>array(
                    'method'=>"GET",
                    'header'=>"Content-Type: application/json en\r\n" .
                    "Authorization: Token ".$token."\r\n"
                )
            );

$response = file_get_contents($Base_URL."?format=json", false, stream_context_create($opts));

echo $response;

您可以将 headers 添加到 file_get_contents,它需要一个名为 context 的参数,可用于此:

$url = BASE_URL . 'api/v1/users';
$options = array('http' => array(
    'method'  => 'GET',
    'header' => 'Authorization: Bearer '.$token
));
$context  = stream_context_create($options);
$response = file_get_contents($url, false, $context);

您的问题可能与您的授权有关,您知道服务器中的授权类型吗?

可能你的类型是cn389ncoiwuencr,从服务器说一下试试:

'header' => 'Authorization: Bearer cn389ncoiwuencr '.$token

我发现这是影响 header 授权的 apache 和 php 服务器配置,我能够使用 .htaccess

覆盖它

我在 .htaccess 中添加了这一行

SetEnvIf Authorization "(.*)" HTTP_AUTHORIZATION=