如果file_get_contents返回“ HTTP请求失败!HTTP / 1.1 403”是什么意思?

时间:2018-08-11 22:26:18

标签: php api github oauth

似乎每次都会出现此错误

 file_get_contents(https://api.github.com/users/AnyUsername/following): failed 
 to open stream: HTTP request failed! HTTP/1.1 403 Forbidden in 
 C:\xampp\htdocs\Github\test.php on line 40

下面是一些代码行:

$data = array(
'client_id' => 'a7f10b4ef02b11843ae7',
'client_secret' => '89b227cbb3705099c7281ba367cfc5f868ea4f4b',
'redirect_uri'=>'http://localhost/Github/test.php',
'code'=>$code,

);

$post=http_build_query($data);
$url="https://github.com/login/oauth/access_token?".$post;
$contents=file_get_contents($url);
$explode1 = explode('access_token=', $contents);
$explode2 = explode('&scope=user', $explode1[1]);
$access_token = $explode2[0];
$opts = [ 'http' => [
           'method' => 'GET',
           'header' => [ 'User-Agent: PHP']
                ]
    ];
    //fetching user data
$url = "https://api.github.com/user?access_token=".$access_token;
$context = stream_context_create($opts);
$data = file_get_contents($url, false, $context);
$user_data = json_decode($data, true);
$_SESSION['user'] = $user_data['login'];
$_SESSION['email']=$user_data['email'];
$img=$user_data['avatar_url'];
$name=$user_data['name'];

    //fetching user following
$url="https://api.github.com/users/".$_SESSION['user']."/following";
$context = stream_context_create($opts);
$data = file_get_contents($url, false, $context);
$user_data = json_decode($data, true);

错误在第二行,通常是GitHub API 通过PHP。

2 个答案:

答案 0 :(得分:1)

尝试

function getSslPage($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.2; WOW64; rv:17.0) Gecko/20100101 Firefox/17.0');
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_REFERER, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$result = curl_exec($ch);
curl_close($ch);
return $result; } echo getSslPage('https://api.github.com/users/TheYkk/following');
  

管理规则禁止的请求。请确保您的请求具有User-Agent标头(http://developer.github.com/v3/#user-agent-required)。检查https://developer.github.com是否有其他可能的原因。

答案 1 :(得分:0)

您似乎没有权限访问指定用户的“关注”列表。

  

HTTP/1.1 403 Forbidden in

我现在仅在浏览器中测试该URL格式,看来我无法查看除我自己的用户之外的任何用户“关注”列表的JSON。