【问题标题】:PHP file_get_contents gives HTTP code 401 UnauthorizedPHP file_get_contents 给出 HTTP 代码 401 Unauthorized
【发布时间】:2018-03-24 22:30:24
【问题描述】:

我尝试发出经过身份验证的 HTTP GET 请求,但收到 401 HTTP 错误。我确信签名是正确的。因此,我认为问题出在第 18 行的多个标题中。但不幸的是,我找不到确切的问题。

警告:file_get_contents(http://test.com/path):打开流失败:HTTP 请求失败! HTTP/1.1 401 Unauthorized in /home/host/path.php 第 22 行

<?php
$apiKey = '1';
$apiSecret = '2';

$verb = 'GET';

$path = '/path';
$nonce = '1';
$data = '';

$signature = hash_hmac('sha256', $verb . $path . $nonce . $data, $apiSecret);

$url="http://test.com/path"; 

$opts = [
    "http" => [
        "method" => $verb,
        "header" => "api-nonce: ".$nonce. "\r\n", "api-key: " .$apiKey. "\r\n", "api-signature: " . $signature
    ]
];
$context = stream_context_create($opts);
$json = file_get_contents($url, false, $context);

if($json){
    $data = @json_decode($json, TRUE);

    print_r($data);
}
?>

【问题讨论】:

    标签: php file-get-contents http-status-code-401


    【解决方案1】:

    第 18 行的格式错误。 您使用逗号分隔标题,而应该将它们连接为一个字符串:

    "header" => "api-nonce: ".$nonce. "\r\n" . "api-key: " .$apiKey. "\r\n" . "api-signature: " . $signature . "\r\n"
    

    【讨论】:

    • 谢谢!现在完美运行。
    猜你喜欢
    • 2010-10-18
    • 1970-01-01
    • 2019-07-12
    • 1970-01-01
    • 2016-11-28
    • 1970-01-01
    • 2020-06-01
    • 2011-03-18
    相关资源
    最近更新 更多