列出腾讯云存储的文件


使用腾讯云 COS API 查看存储里的所有文件(最多1000个)

define('SecretId', 'SecretId');
define('SecretKey', 'SecretKey');

function listBucketFiles($region, $bucket)
{

    $host = $bucket . '.cos.' . $region . '.myqcloud.com';
    $path = '/';
    $url = 'https://' . $host . $path;
    $header = array(
        'Authorization: ' . requestSign($host, 'GET', $path),
        'Date: ' . gmdate('D, d M Y H:i:s T'),
    );

    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
    $response = curl_exec($curl);
    curl_close($curl);

    $files = [];
    $list = simplexml_load_string($response);
    foreach ($list->Contents as $v) {
        $files[] = (String) $v->Key;
    }

    return $files;
}

function requestSign($host, $method, $path)
{
    $signTime = (string) (time() - 60) . ';' . (string) (time() + 1200);
    $httpString = sprintf("%s\n%s\n\nhost=%s\n", strtolower($method), $path, $host);
    $stringToSign = sprintf("sha1\n%s\n%s\n", $signTime, sha1($httpString));
    $signKey = hash_hmac('sha1', $signTime, SecretKey);
    $signature = hash_hmac('sha1', $stringToSign, $signKey);
    return sprintf('q-sign-algorithm=sha1&q-ak=%s&q-sign-time=%s&q-key-time=%s&q-header-list=host&q-url-param-list=&q-signature=%s', SecretId, $signTime, $signTime, $signature);
}