phpgithubgithub-apiphp-curlhttp-redirect

Get download link from private repo


In PHP, I'm trying to get the download link from my private repo with Github API.

I have refer to this doc: https://docs.github.com/en/rest/repos/contents?apiVersion=2022-11-28#download-a-repository-archive-zip

I plan to use cURL in PHP, but I have no idea how to retrive/generate a temporary download link. I have tried to echo the $response directly, it seems the code are all unknown characters.

Below is my code:

$token = 'abcdef';
$url   = 'https://api.github.com/repos/meiuser/ai/zipball';
$ch    = curl_init();

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Accept: application/vnd.github+json',
    'Authorization: Bearer ' . $token,
    'X-GitHub-Api-Version: 2022-11-28',
    'User-Agent: ai'
]);

$response = curl_exec($ch);

curl_close($ch);

Solution

  • Since you've set cURL to follow Location headers, it will have silently gone to the URL provided by the API (as per that documentation) and then downloaded the result - those characters you're seeing are the binary content of the zip file which the download link points to.

    If you want the download link instead, tell curl not to follow the redirect. Then get the link from the Location header returned by the initial request.

    These steps should help you:

    Remove this line, which tells cURL to follow redirects:

    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    

    And add this after the curl_exec command:

    $info = curl_getinfo($ch, CURLINFO_REDIRECT_URL);
    echo $info;