file_get_contents() gets 403 from api.github.com every time

风格不统一 提交于 2019-12-10 02:07:54

问题


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.

This works

  • 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

This works not

  • with a simple file_get_contents()from a PHP-Skript

This is my whole simplified code:

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

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.

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.


回答1:


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

The output is:

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


来源:https://stackoverflow.com/questions/37141315/file-get-contents-gets-403-from-api-github-com-every-time

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!