通过 PHP 下载 Github Release 资产文件

Posted

技术标签:

【中文标题】通过 PHP 下载 Github Release 资产文件【英文标题】:Download Github Release asset file via PHP 【发布时间】:2021-05-20 06:29:57 【问题描述】:

我正在使用 PHP Github API 来列出我的版本。现在我需要将一个资产文件从最新版本复制到我的服务器。

php Github API 不提供下载功能,所以我决定直接发出 cURL 请求。

这是我的自动取款机:

<pre>
<?php

// This file is generated by Composer
require_once '../vendor/autoload.php';

$client = new \Github\Client();
$client->authenticate(':mytoken', null, Github\Client::AUTH_ACCESS_TOKEN);
$release = $client->api('repo')->releases()->latest('arminetsw', 'webstore');
$nombre_fichero = $release['assets'][0]['name'];
$download_url = $release['assets'][0]['browser_download_url'];
$download_url = 'https://api.github.com/repos/arminetsw/webstore/releases/assets/:myAssetId?access_token=:mytoken';

$cliente = curl_init();
$file = fopen("webstore.zip", 'w');
curl_setopt($cliente, CURLOPT_URL, "https://api.github.com/repos/arminetsw/webstore/releases/assets/32188729?access_token=:mytoken");
curl_setopt($cliente, CURLOPT_HEADER, 'Accept: application/octet-stream');
curl_setopt($cliente, CURLOPT_USERAGENT, 'Webstore');
curl_exec($cliente);
curl_close($cliente);
fclose($file);

//$nuevo_fichero = ''

/*if (!copy($download_url, $nombre_fichero)) 
    echo "Error al copiar $nombre_fichero...\n";
*/

var_dump($release);

?>
</pre>

我只得到一个没有错误的 webstore.zip 0 字节文件。

*repo 是私有的。

【问题讨论】:

【参考方案1】:

最终工作代码:

<pre>
<?php

set_time_limit(0);

require_once '../vendor/autoload.php';

$client = new \Github\Client();
$client->authenticate('XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', null, Github\Client::AUTH_ACCESS_TOKEN);
$release = $client->api('repo')->releases()->latest('user', 'repo');
$nombre_fichero = $release['assets'][0]['name'];
$download_url = $release['assets'][0]['url'];
$authorization = "access_token=XXXXXXXXXXXXXXXXXXXXXXXXXXXX";
$download_url .= "?" . $authorization;

$file = fopen($nombre_fichero, 'w');
$curl = curl_init();

curl_setopt_array($curl, [
  CURLOPT_URL => $download_url,
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_FOLLOWLOCATION => true,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "GET",
  CURLOPT_POSTFIELDS => "",
  CURLOPT_USERAGENT => "Webstore",
  CURLOPT_FILE => $file,
  CURLOPT_HTTPHEADER => [
    "Accept: application/octet-stream",
    "Content-Type: application/octet-stream"
  ],
]);

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

fputs($file, $response);
fclose($file);

if ($err) 
  echo "cURL Error #:" . $err;
 else 
  echo $response;


?>
</pre>

【讨论】:

以上是关于通过 PHP 下载 Github Release 资产文件的主要内容,如果未能解决你的问题,请参考以下文章

Github下载release附件变相提速方法

github release 文件下载贼慢,干脆失败的解决方法

github release使用

cppMicroService 下载编译

Nacos下载和安装步骤

ubuntu下安装memcached和PHP的memcache扩展