每次file_get_contents()从api.github.com获取403 [英] file_get_contents() gets 403 from api.github.com every time
问题描述
我称自己是一位经验丰富的PHP开发人员,但这使我发疯.我试图获取用于显示更新警告的存储库的发行信息,但我一直返回403错误.为了简化它,我使用了GitHub API的最简单用法:GET https://api.github.com/zen一个>.真是个好世界.
I call myself an experienced PHP developer, but this is one drives me crazy. I'm trying to get release informations of a repository for displaying update-warnings, but I keep returning 403 errors. For simplifying it I used the most simple usage of GitHubs API: GET https://api.github.com/zen. It is kind of a hello world.
这有效
- 直接在浏览器中
- 在终端中带有普通
curl https://api.github.com/zen
- 具有类似 php-github-api 的PHP-Github-API-Class
- directly in the browser
- with a plain
curl https://api.github.com/zen
in a terminal - with a PHP-Github-API-Class like php-github-api
这行不通
- 使用来自PHP-Skript的简单
file_get_contents()
这是我的整个简化代码:
This is my whole simplified code:
<?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
.
The browser shows Warning: file_get_contents(https://api.github.com/zen): failed to open stream: HTTP request failed! HTTP/1.0 403 Forbidden
, the variable $content
is a boolean and false
.
我想我缺少某种http-header-fields,但是我也找不到 API-Docs ,也不会使用我的终端curl
调用任何特殊的头文件并起作用.
I guess I'm missing some sort of http-header-fields, but neither can I find those informations in the API-Docs, nor uses my terminal curl
-call any special header files and works.
推荐答案
之所以会发生这种情况,是因为GitHub要求您发送UserAgent标头.不需要任何特定的内容.可以做到:
This happens because GitHub requires you to send UserAgent header. It doesn't need to be anything specific. This will do:
$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."
这篇关于每次file_get_contents()从api.github.com获取403的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!