我一直收到这个错误
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/