

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

# 使用 适用于 PHP 的 AWS SDK 版本 3 来配置 Amazon S3 存储桶
<a name="s3-examples-configuring-a-bucket"></a>

跨源资源共享 (CORS) 定义了在一个域中加载的客户端 Web 应用程序与另一个域中的资源交互的方式。借助 Amazon S3 中的 CORS 支持，您可以使用 Amazon S3 来构建各种富客户端 Web 应用程序，并选择性地允许跨源访问您的 Amazon S3 资源。

有关将 CORS 配置用于 Amazon S3 存储桶的更多信息，请参阅[跨源资源共享 (CORS)](https://docs.aws.amazon.com/AmazonS3/latest/dev/cors.html)。

以下示例演示如何：
+ 使用 [GetBucketCors](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-s3-2006-03-01.html#getbucketcors) 获取存储桶的 CORS 配置。
+ 使用 [PutBucketCors](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-s3-2006-03-01.html#putbucketcors) 设置用于存储桶的 CORS 配置。

适用于 PHP 的 AWS SDKGitHub[ 上提供了](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code)的所有示例代码。

## 凭证
<a name="examplecredentials"></a>

运行示例代码之前，请配置您的 AWS 凭证，如 [AWS 使用 适用于 PHP 的 AWS SDK 版本 3 进行身份验证](credentials.md) 中所述。然后导入 适用于 PHP 的 AWS SDK，如 [安装 适用于 PHP 的 AWS SDK 版本 3](getting-started_installation.md) 中所述。

## 获取 CORS 配置
<a name="get-the-cors-configuration"></a>

使用以下代码创建 PHP 文件。首先创建一个 AWS.S3 客户端服务，然后调用 `getBucketCors` 方法并指定使用所需 CORS 配置的存储桶。

需要的唯一参数是所选存储桶的名称。如果存储桶当前具有 CORS 配置，该配置将作为 [CORSRules 对象](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-s3-2006-03-01.html#shape-corsrule)由 Amazon S3 返回。

 **导入**。

```
require 'vendor/autoload.php';

use Aws\Exception\AwsException;
use Aws\S3\S3Client;
```

 **示例代码** 

```
$client = new S3Client([
    'profile' => 'default',
    'region' => 'us-west-2',
    'version' => '2006-03-01'
]);

try {
    $result = $client->getBucketCors([
        'Bucket' => $bucketName, // REQUIRED
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    error_log($e->getMessage());
}
```

## 设置 CORS 配置
<a name="set-the-cors-configuration"></a>

使用以下代码创建 PHP 文件。首先创建一个 AWS.S3 客户端服务。然后，调用 `putBucketCors` 方法并指定要设置其 CORS 配置的存储桶，并将 CORS 配置设置为 [CORSRules JSON 对象](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-s3-2006-03-01.html#shape-corsrule)。

 **导入**。

```
require 'vendor/autoload.php';

use Aws\Exception\AwsException;
use Aws\S3\S3Client;
```

 **示例代码** 

```
$client = new S3Client([
    'profile' => 'default',
    'region' => 'us-west-2',
    'version' => '2006-03-01'
]);

try {
    $result = $client->putBucketCors([
        'Bucket' => $bucketName, // REQUIRED
        'CORSConfiguration' => [ // REQUIRED
            'CORSRules' => [ // REQUIRED
                [
                    'AllowedHeaders' => ['Authorization'],
                    'AllowedMethods' => ['POST', 'GET', 'PUT'], // REQUIRED
                    'AllowedOrigins' => ['*'], // REQUIRED
                    'ExposeHeaders' => [],
                    'MaxAgeSeconds' => 3000
                ],
            ],
        ]
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    error_log($e->getMessage());
}
```