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

标签 php github-api

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

这行得通

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

这行不通

  • 使用来自 PHP 脚本的简单 file_get_contents()

这是我的整个简化代码:

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

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

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

最佳答案

发生这种情况是因为 GitHub 要求您发送 UserAgent header 。它不需要是任何特定的。这将做到:

$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."

关于php - file_get_contents() 每次都从 api.github.com 获取 403,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37141315/

相关文章:

php - 如何根据当天重新排列网页上列表的顺序?

php - 如何向数据库添加多个 INT?

github-api - Probot 应用程序在尝试合并 PR 时抛出 "Resource Not Accessible By Integration"

github - 获取github secret值的方法

python - 使用 Github API 获取所有存储库的最后一次提交

javascript - 使用客户端 Javascript 和 OAuth.io 使用 GitHub API fork 存储库

php - CodeIgniter 动态方法调用

php - js - 使用 jquery 设置 var = 元素的宽度

php - 如何检查bean是否相关

curl - 如何在 Postman 中使用 GitHub API