如何在php上使用cURL下载我的私有github存储库的.zip?

时间:2017-08-21 21:08:26

标签: php curl github

我想下载我正在处理的私有github存储库的最新zip版本,我想使用PHP脚本执行此操作。但是,我当前的PHP脚本只是返回“Not Found” - 我猜我的cURL用户/传递设置存在问题,但我无法弄明白。我目前的代码如下:

$username='XXX';
$password='XXX';
$URL='https://github.com/[user]/[reponame]/archive/master.zip';

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$URL);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
$result=curl_exec ($ch);

file_put_contents('master.zip', $result);
curl_close ($ch);

3 个答案:

答案 0 :(得分:0)

我能够通过将登录页面和文件下载页面分成两个请求来使其工作。以下代码对我有用:

$username='XXX';
$password='XXX';
$URL='https://github.com/[user]/[reponame]/archive/master.zip';

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,'https://github.com');
curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");

curl_setopt($ch, CURLOPT_URL,$URL);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

$result=curl_exec ($ch);
curl_close ($ch);


file_put_contents('master.zip', $result);

答案 1 :(得分:0)

除了您的回答,如果您想下载较大的文件以节省内存,我建议您使用以下内容。

$fp = fopen ('master.zip', 'w+');
curl_setopt($ch, CURLOPT_FILE, $fp); 

答案 2 :(得分:0)

我知道这个问题有点老了,但值得注意的是,GitHub允许生成允许您下载私人回购的OAuth密钥。这样您就无法在代码中保留用户名和密码 对于未来的搜索者,下面是使用生成的OAuth访问令牌的示例代码 问题是拉链功能,但API也允许tarball。

 $fp = fopen('/path/to/yourfile.zip', 'w+');
 $giturl = 'https://api.github.com/repos/{username}/{reponame}/zipball/master?access_token={YourTokenHere}';
 $ch = curl_init($giturl);
 //set file to write to
 curl_setopt($ch, CURLOPT_FILE, $fp);
 //the API will not allow you to download without a user agent so CURLOPT_USERAGENT is important.
 curl_setopt($ch, CURLOPT_USERAGENT, 'PHP/'.phpversion('tidy'));
 //The API URL redirects so the following line is very important
 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
 $output = curl_exec($ch);

 if(curl_errno($ch)){
     throw new Exception(curl_error($ch));
 }

 //Get the HTTP status code.
 $statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

 //Close the cURL handler.
 curl_close($ch);

 //Output result
 if($statusCode == 200){
     echo 'Downloaded Successfully';
 } else{
     echo "Failed downloading - Status Code: " . $statusCode;
 }