PHP file_get_contents提供HTTP代码401 Unauthorized

时间:2017-10-12 21:04:50

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

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

  

警告:file_get_contents(http://test.com/path):无法打开流:HTTP请求失败!第22行/home/host/path.php中未经授权的HTTP / 1.1 401

<?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);
}
?>

1 个答案:

答案 0 :(得分:1)

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

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