0

我的需求很简单......人们会想。我只是想用 PHP 脚本创建一个签名的 URL,以防止下载滥用托管在 Google Cloud Storage 上的文件。我找到了几个例子,没有一个有效。这个最接近:

<?php

$filepath = 'my file.zip'; // do not include the bucket name, no slash in the beginning
$bucket = 'mybucket';
$key = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXX'; // key
$secret = 'xxxxxxxxxxxxxxxxxxxxxxx'; // secret

function getSignedGoogleCloudStorageUrl($filepath, $bucket, $secret, $key, $duration = 300)
{
    $expires = new \DateTime('+ ' . $duration . ' seconds');
    $seconds = $expires->format('U');

    $objectPieces = explode('/', $filepath);
    array_walk($objectPieces, function (&$piece) {
        $piece = rawurlencode($piece);
    });
    $objectName = implode('/', $objectPieces);

    $resource = sprintf(
        '/%s/%s',
        $bucket,
        $objectName
    );

    $headers = []; // you may add any headers needed here

    $toBeSignedArray = [
        'GET',
        '', // contentMd5, can be left blank
        '', // contentType, can be left blank
        $seconds,
        implode("\n", $headers) . $resource,
    ];

    $toBeSignedString = implode("\n", $toBeSignedArray);
    $encodedSignature = urlencode(base64_encode(hash_hmac('sha1', $toBeSignedString, $secret, true)));

    $query   = [];
    $query[] = 'GoogleAccessId=' . $key;
    $query[] = 'Expires=' . $seconds;
    $query[] = 'Signature=' . $encodedSignature;

    return "https://storage.googleapis.com/{$bucket}/{$filepath}?" . implode('&', $query);
}

echo getSignedGoogleCloudStorageUrl($filepath, $bucket, $secret, $key);

?>

但是,它在第​​一次使用后总是产生相同的结果,直到我清除 Web 服务器上的缓存。

任何帮助或其他工作示例都会很棒。谢谢。

4

0 回答 0