使用 JSON 密钥的 PHP curl 访问 GCP 存储桶文件

我是 GCP 的新手。我有一个将 CSV 文件输出到 GCP 云存储的功能。我正在尝试使用 PHP 访问该文件。

到目前为止我做了什么:

  1. 我使用 GCP IAM 创建了一个服务帐户,并授予它作为存储对象查看器的访问权限。

  2. 我还从 IAM 获得了 json 密钥。

我需要在我的 PHP 脚本(托管在不同的 Web 服务器上)中使用哪些命令来使用 CURL 检索文件以及如何使用 json 身份验证密钥?

如果这在某处的文档中,我提前道歉,我发现它非常复杂且令人不知所措。任何建议或方向表示赞赏。


更新:

根据下面的评论,这里是我找到的google-cloud-php github的链接。我不确定这是否是开始的最佳资源。


蓝山帝景
浏览 131回答 2
2回答

扬帆大鱼

您可以使用 php 的Cloud Storage 库,更具体地说,如何下载对象。

白衣染霜花

首先,您必须获得一个访问令牌以进行身份验证。为此,您需要 json 身份验证密钥。此页面对我有很大帮助: https ://www.it-swarm.dev/de/curl/wie-kann-man-mit-curl-eine-verbindung-zum-google-drive-api-herstellen/806069468 /也许这个 PHP 代码可以帮助你一点:    function get_Google_accesstoken($scope,$credfile,$proxy,$timetoexpiration){    #Developers Info at developers.google.com/identity/protocols/oauth2/service-account        $GoogleApiKeyInfo=GoogleApiKeyInfo($credfile);        $Header=array();        $Header["alg"]="RS256";        $Header["typ"]="JWT";        $ClaimSet["iss"]=$GoogleApiKeyInfo["client_email"];        $ClaimSet["scope"]=$scope;        $ClaimSet["aud"]=$GoogleApiKeyInfo["token_uri"];        $ClaimSet["iat"]=time();        $ClaimSet["exp"]=$ClaimSet["iat"]+($timetoexpiration);        $Jws=base64_encode(json_encode($Header)).".".base64_encode(json_encode($ClaimSet));        $OpenSslRslts=openssl_sign($Jws,$Signature,$GoogleApiKeyInfo["private_key"],OPENSSL_ALGO_SHA256);        $Jwt=$Jws.".".base64_encode($Signature);        $SendVars=array();        $SendVars["grant_type"]=("urn:ietf:params:oauth:grant-type:jwt-bearer");        $SendVars["assertion"]=$Jwt;        $SendVars=http_build_query($SendVars);        $ch=curl_init();        curl_setopt($ch, CURLOPT_URL, $GoogleApiKeyInfo["token_uri"]);    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);    curl_setopt($ch, CURLOPT_PROXY, $proxy);    curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_HTTP);    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);    curl_setopt($ch, CURLOPT_POST, 1);    curl_setopt($ch, CURLOPT_POSTFIELDS, $SendVars);    $headers = array();    $headers[] = 'Content-Type: application/x-www-form-urlencoded';    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);    $response = curl_exec($ch);    if (curl_errno($ch)){    echo 'Error:' . curl_error($ch);    }    curl_close($ch);    $response=json_decode($response);    return $response;}您可以在developers.google.com/identity/protocols/oauth2/scopes找到 $scope 的提示 $proxy 仅在您需要代理且 $timetoexpiration 没有影响时使用,因为您的 accesstoken 始终有效 60 分钟
打开App,查看更多内容
随时随地看视频慕课网APP