skip to Main Content

Based on https://docs.github.com/en/rest/commits/commits?apiVersion=2022-11-28 I have this code:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.github.com/repos/octocat/Hello-World/commits");
$headers = [
    'Accept: application/vnd.github+json',
    'Authorization: Bearer <my personal token>',
    'X-GitHub-Api-Version: 2022-11-28'
];

curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$server_output = curl_exec($ch);
curl_close($ch);
print $server_output ;

But it does not return anything. It’s white page. If I access the url in the browser directly I am able to see the response from the API.

What am I doing wrong ?

2

Answers


  1. Chosen as BEST ANSWER

    I have managed to make it work. Besides the user agent I had set this option:

    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    

    Without this, it doesn't work for me.


  2. GitHub requires you to send a User-Agent:

    Request forbidden by administrative rules.
    Please make sure your request has a User-Agent header
    (https://docs.github.com/en/rest/overview/resources-in-the-rest-api#user-agent-required).

    Apparently PHP’s curl module does not automatically send one. Setting the User-Agent header manually via

    $headers = [
      …
      'User-Agent: curl'
    ];
    

    or

    curl_setopt($ch, CURLOPT_USERAGENT, "curl");
    

    works for me.


    Simplified working example:

    <?php
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "https://api.github.com/repos/octocat/Hello-World/commits");
    curl_setopt($ch, CURLOPT_USERAGENT, "curl");
    curl_exec($ch);
    curl_close($ch);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search