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

前端 未结 1 1786
醉梦人生
醉梦人生 2021-02-13 03:57

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 r

1条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-13 04:40

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

    0 讨论(0)
提交回复
热议问题