php - file_get_contents 不适用于承载

标签 php slim middleware

我一直收到这个错误

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 接受授权;

如果我在参数中使用 token ,它可以工作但不能通过服务器上的 header 发送它,导致在本地主机上它工作,

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

知道为什么吗?在不更改所有 curl 请求的情况下我能做什么

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

最佳答案

您可以将 header 添加到 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);

关于php - file_get_contents 不适用于承载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45409522/

相关文章:

web-services - 将 SOAP 转换为 REST

php - 使用php Auth0 mysql连接错误

php - 标记记录已插入

php - 无法访问 Twig 上的 Eloquent 属性

php - 在瘦框架的 route 找不到类异常

php - 将参数传递给Laravel中的中间件

php - 网站首页显示数据库高亮需要SQL

php - 方法重构?

php - Slim Framework - 将代码拆分为 index.php 以外的多个文件

django - 在 Django 中间件中测量 View 执行时间 - 好主意吗?