php - AWS S3 - 使用 PHP SDK2 设置元数据

标签 php amazon-web-services amazon-s3

我正在尝试使用 AWS PHP SDK2 更改 S3 上特定存储桶中所有对象的元数据。我很难找到使用新 SDK 的特定示例,但拼凑了以下内容:

$OBJ_aws_s3 = S3Client::factory($config);

$objects = $OBJ_aws_s3->getIterator('ListObjects', array(
    'Bucket' => $bucket,
    'MaxKeys' => 10
));

foreach($objects as $object) {
    $key = $object['Key'];

    echo "Processing " . $key . "\n";

    $response = $OBJ_aws_s3->copyObject(array(
        'Bucket' => $bucket, 
        'Key' => $key,
        'CopySource' => $key,
        'Metadata' => array(
            'Cache-Control' => 'max-age=94608000',
            'Expires' => gmdate('D, d M Y H:i:s T', strtotime('+3 years'))
        ),
        'MetadataDirective' => 'REPLACE',
    ));
}

foreach 循环成功地循环了给定 $bucket 中的前 10 个项目,但是我在 copyObject() 操作中遇到了 403 错误:

Uncaught Aws\S3\Exception\AccessDeniedException: AWS Error Code: AccessDenied, Status Code: 403

我不确定这是由于传递给 copyObject 的值不正确,还是由于 S3 中的某些设置。请注意,我尚未在 IAM 中创建一个权限受限的帐户,并且正在使用应该对对象拥有所有权限的基本帐户。

感谢任何帮助。

最佳答案

好的,明白了——我的语法在两个方面是不正确的。

首先,我为 CopySource 使用了错误的值。来自documentation :

CopySource - (string) - The name of the source bucket and key name of the source object, separated by a slash (/). Must be URL-encoded.

所以在我的例子中,不是只使用 'CopySource' => $key,,它应该是 'CopySource' => urlencode($bucket . '/' . $key ),。这解释了 403 错误,因为我实际上是在告诉 API 我的源文件位于 {bucket}/{key} 中,只有 {key}。

第二个问题与特定 header 有关 - 在 Metadata 字段中指定 Expires 和 Cache-Control header 会导致创建亚马逊特定的元值,键以 x 为前缀-amz-元-。相反,我现在使用 ExpiresCacheControl 参数。我的最终工作代码:

$OBJ_aws_s3 = S3Client::factory($config);

$objects = $OBJ_aws_s3->getIterator('ListObjects', array(
    'Bucket' => $bucket,
    'MaxKeys' => 10
));

foreach($objects as $object) {
    $key = $object['Key'];

    echo "Processing " . $key . "\n";

    $response = $OBJ_aws_s3->copyObject(array(
        'Bucket' => $bucket, 
        'Key' => $key,
        'CopySource' => urlencode($bucket . '/' . $key),
        'CacheControl' => 'max-age=94608000',
        'Expires' => gmdate('D, d M Y H:i:s T', strtotime('+3 years')),
        'MetadataDirective' => 'COPY',
    ));
}

关于php - AWS S3 - 使用 PHP SDK2 设置元数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16504091/

相关文章:

php - 边框图像和背景颜色填充

php - REST 应用程序 + codeigniter + 数据库

javascript - 为什么使用 AWS Signature v4 对 S3 进行 REST 调用并未真正使用签名过程?

sql - 数据库设计和文件存储服务器

amazon-web-services - 安装在 EC2 服务器中时适用的 Amazon S3 Bucket 数据传输费用?

php - PHP 插入到 SQL 的问题

带有 mod_fcgid 的 php5 导致 500 错误 - 可能是错误的权限

php - SQLSTATE[HY000] [2003] 无法连接到 MySQL 服务器

wordpress - AWS EC2 Ubuntu 文件权限问题

amazon-web-services - Google Cloud的Cloud Run与无尽技术的可扩展性有何不同?