file_get_contents()每次从api.github.com获取403

时间:2016-05-10 14:22:56

标签: php github-api

我称自己是一位经验丰富的PHP开发人员,但这让我感到疯狂。我试图获取存储库的发布信息以显示更新警告,但我一直在返回403错误。为了简化它,我使用了GitHubs API的最简单用法:GET https://api.github.com/zen。这是一个你好世界。

这有效

  • 直接在浏览器中
  • 在终端中使用普通curl https://api.github.com/zen
  • 使用PHP-Github-API-Class,如php-github-api

这不起作用

  • 使用来自PHP-Skript的简单file_get_contents()

这是我的简化代码:

<?php
    $content = file_get_contents("https://api.github.com/zen");
    var_dump($content);
?>

浏览器显示Warning: file_get_contents(https://api.github.com/zen): failed to open stream: HTTP request failed! HTTP/1.0 403 Forbidden,变量$content是布尔值,false

我想我错过了某种http-header-fields,但我无法在API-Docs中找到这些信息,也无法使用我的终端curl - 调用任何特殊的头文件和工作。

1 个答案:

答案 0 :(得分:16)

这是因为GitHub要求您发送UserAgent标头。它不需要任何具体的东西。这样做:

$opts = [
        'http' => [
                'method' => 'GET',
                'header' => [
                        'User-Agent: PHP'
                ]
        ]
];

$context = stream_context_create($opts);
$content = file_get_contents("https://api.github.com/zen", false, $context);
var_dump($content);

输出结果为:

string(35) "Approachable is better than simple."