Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

github-api

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.

like image 903
Cologne_Muc Avatar asked May 10 '16 14:05

Cologne_Muc


1 Answers

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."
like image 148
Aleksander Wons Avatar answered Sep 22 '22 21:09

Aleksander Wons