Looking at docs I can download my git repo zip file using:
curl -L -H "Accept: application/vnd.github+json" -H "Authorization: Bearer <MY TOKEN>" -H "X-GitHub-Api-Version: 2022-11-28" https://api.github.com/repos/<MY_GIT_NAME>/<REPO>/zipball/master --output "download.zip"
I want to use this curl from within a PHP function:
$f = fopen(__DIR__.'/download.zip', 'w+');
$ch = curl_init();
$url = "https://api.github.com/repos/$user/$repo/zipball/master";
$opt = [
CURLOPT_URL => $url,
CURLOPT_CUSTOMREQUEST => 'GET',
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_FILE => $f,
];
curl_setopt_array($ch, $opt);
$headers = array(
"Accept: application/vnd.github+json",
"Authorization: Bearer $token",
"X-Github-Api-Version: 2022-11-28",
);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
curl_close($ch);
The $response is true but the zip file empty. Any ideas?
UPDATE
I am pretty sure the issue is with the curl, as it takes no time at all to execute, whereas a few seconds on the command line. Looking at the curl_getinfo as suggested it looks like I am getting http_code: 403.
I have tried adding:
$userAgent = $_SERVER['HTTP_USER_AGENT'];
and then
"User-Agent: $userAgent"
into the headers and then get http_code: 302
2
Answers
Add the following line after the curl_exec() function:
rewind($f);
This will move the file pointer back to the beginning of the file, allowing you to read the downloaded data.
Also, make sure that you have write permissions for the directory where you are trying to save the downloaded file.
Ok, so if the request is successful, it will send a
302
redirect as mentioned in thedocs
.To control this, we will use
CURLOPT_FOLLOWLOCATION
to catch the binary response thrown for the zip file.At my end, I was forced to add
User-Agent
header too without which I got the request forbidden error. So, added aUser-Agent
as mentioned in thedocs
.Once the binary data is received, just write that in a
.zip
file name of your choice usingfile_put_contents
. Below is the code that works perfectly fine at my end.Final code:
Note: If you are unsure about the
ref
branch, just skip it so that the git system takes the default branch. From thedocs
,