

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

# 带有适用于 适用于 PHP 的 AWS SDK 的指导的代码示例
<a name="examples_index"></a>

本节包含了演示使用 适用于 PHP 的 AWS SDK 的常见 AWS 场景的代码示例。

适用于 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) 中所述。

**Topics**
+ [凭证](#examplecredentials)
+ [Amazon CloudFront 示例](cf-examples.md)
+ [Amazon CloudSearch](service_cloudsearch-custom-requests.md)
+ [Amazon CloudWatch 示例](cw-examples.md)
+ [Amazon EC2 示例](ec2-examples.md)
+ [Amazon OpenSearch Service](service_es-data-plane.md)
+ [AWS Identity and Access Management 示例](iam-examples.md)
+ [AWS Key Management Service](kms-examples.md)
+ [Kinesis 示例](kinesis-examples.md)
+ [AWS Elemental MediaConvert](emc-examples.md)
+ [Amazon S3 示例](s3-examples.md)
+ [AWS Secrets Manager](secretsmanager-examples-manage-secret.md)
+ [Amazon SES 示例](ses-examples.md)
+ [Amazon SNS 示例](sns-examples.md)
+ [Amazon SQS 示例](sqs-examples.md)
+ [Amazon EventBridge](eventbridge-examples.md)

# 使用 适用于 PHP 的 AWS SDK 版本 3 的 Amazon CloudFront 示例
<a name="cf-examples"></a>

Amazon CloudFront 是一项 AWS Web 服务，可加快从您自己的 Web 服务器或 AWS 服务器（例如 Amazon S3）提供静态和动态 Web 内容的速度。CloudFront 通过全球数据中心（称作边缘站点）网络来传输内容。当用户请求您通过 CloudFront 分发的内容时，将被引导至提供最低延迟的边缘站点。如果内容尚未在该处缓存，CloudFront 将从原始服务器检索副本，处理副本，然后将其缓存以供将来的请求使用。

有关 CloudFront 的更多信息，请参阅 [Amazon CloudFront 开发人员指南](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/)。

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

# 使用 CloudFront API 和 适用于 PHP 的 AWS SDK 版本 3 来管理 Amazon CloudFront 分配
<a name="cloudfront-example-distribution"></a>

Amazon CloudFront 将内容缓存在全球边缘站点中，以加快您存储在自己的服务器或 Amazon 服务（如 Amazon S3 和 Amazon EC2）上的静态和动态文件的分配速度。当用户从您的网站请求内容时，CloudFront 将从最近的边缘站点提供内容（如果文件已在该处缓存）。否则，CloudFront 将检索文件的副本，处理副本，然后将其缓存以供下一个请求使用。在边缘站点缓存内容将减少该区域中类似用户请求的延迟。

对于您创建的每个 CloudFront 分配，指定内容所在的位置以及如何在用户发出请求时分配内容。本主题重点介绍静态和动态文件（如 HTML、CSS、JSON 和图像文件）的分配。有关结合使用 CloudFront 与视频点播的信息，请参阅[使用 CloudFront 的视频点播和实时流视频](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/on-demand-streaming-video.html)。

以下示例演示如何：
+ 使用 [CreateDistribution](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-cloudfront-2018-11-05.html#createdistribution) 创建分配。
+ 使用 [GetDistribution](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-cloudfront-2018-11-05.html#getdistribution) 获取分配。
+ 使用 [ListDistributions](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-cloudfront-2018-11-05.html#listdistributions) 列出分配。
+ 使用 [UpdateDistributions](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-cloudfront-2018-11-05.html#updatedistribution) 更新分配。
+ 使用 [DisableDistribution](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-cloudfront-2018-11-05.html#disabledistribution) 禁用分配。
+ 使用 [DeleteDistributions](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-cloudfront-2018-11-05.html#deletedistribution) 删除分配。

适用于 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) 中所述。

有关使用 Amazon CloudFront 的更多信息，请参阅 [Amazon CloudFront 开发人员指南](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/)。

## 创建 CloudFront 分配。
<a name="create-a-cf-distribution"></a>

从 Amazon S3 桶创建分配。在以下示例中，已注释掉可选参数，但显示默认值。要向您的分配添加自定义项，请取消注释 `$distribution` 内的值和参数。

要创建 CloudFront 分配，请使用 [CreateDistribution](https://docs.aws.amazon.com/cloudfront/latest/APIReference/API_CreateDistribution.html) 操作。

 **导入**。

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

use Aws\Exception\AwsException;
```

 **示例代码** 

```
function createS3Distribution($cloudFrontClient, $distribution)
{
    try {
        $result = $cloudFrontClient->createDistribution([
            'DistributionConfig' => $distribution
        ]);

        $message = '';

        if (isset($result['Distribution']['Id'])) {
            $message = 'Distribution created with the ID of ' .
                $result['Distribution']['Id'];
        }

        $message .= ' and an effective URI of ' .
            $result['@metadata']['effectiveUri'] . '.';

        return $message;
    } catch (AwsException $e) {
        return 'Error: ' . $e['message'];
    }
}

function createsTheS3Distribution()
{
    $originName = 'my-unique-origin-name';
    $s3BucketURL = 'amzn-s3-demo-bucket.s3.amazonaws.com';
    $callerReference = 'my-unique-caller-reference';
    $comment = 'my-comment-about-this-distribution';
    $defaultCacheBehavior = [
        'AllowedMethods' => [
            'CachedMethods' => [
                'Items' => ['HEAD', 'GET'],
                'Quantity' => 2
            ],
            'Items' => ['HEAD', 'GET'],
            'Quantity' => 2
        ],
        'Compress' => false,
        'DefaultTTL' => 0,
        'FieldLevelEncryptionId' => '',
        'ForwardedValues' => [
            'Cookies' => [
                'Forward' => 'none'
            ],
            'Headers' => [
                'Quantity' => 0
            ],
            'QueryString' => false,
            'QueryStringCacheKeys' => [
                'Quantity' => 0
            ]
        ],
        'LambdaFunctionAssociations' => ['Quantity' => 0],
        'MaxTTL' => 0,
        'MinTTL' => 0,
        'SmoothStreaming' => false,
        'TargetOriginId' => $originName,
        'TrustedSigners' => [
            'Enabled' => false,
            'Quantity' => 0
        ],
        'ViewerProtocolPolicy' => 'allow-all'
    ];
    $enabled = false;
    $origin = [
        'Items' => [
            [
                'DomainName' => $s3BucketURL,
                'Id' => $originName,
                'OriginPath' => '',
                'CustomHeaders' => ['Quantity' => 0],
                'S3OriginConfig' => ['OriginAccessIdentity' => '']
            ]
        ],
        'Quantity' => 1
    ];
    $distribution = [
        'CallerReference' => $callerReference,
        'Comment' => $comment,
        'DefaultCacheBehavior' => $defaultCacheBehavior,
        'Enabled' => $enabled,
        'Origins' => $origin
    ];

    $cloudFrontClient = new Aws\CloudFront\CloudFrontClient([
        'profile' => 'default',
        'version' => '2018-06-18',
        'region' => 'us-east-1'
    ]);

    echo createS3Distribution($cloudFrontClient, $distribution);
}

// Uncomment the following line to run this code in an AWS account.
// createsTheS3Distribution();
```

## 检索 CloudFront 分配
<a name="retrieve-a-cf-distribution"></a>

要检索指定 CloudFront 分配的状态和详细信息，请使用 [GetDistribution](https://docs.aws.amazon.com/cloudfront/latest/APIReference/API_GetDistribution.html) 操作。

 **导入**。

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

use Aws\Exception\AwsException;
```

 **示例代码** 

```
function getDistribution($cloudFrontClient, $distributionId)
{
    try {
        $result = $cloudFrontClient->getDistribution([
            'Id' => $distributionId
        ]);

        $message = '';

        if (isset($result['Distribution']['Status'])) {
            $message = 'The status of the distribution with the ID of ' .
                $result['Distribution']['Id'] . ' is currently ' .
                $result['Distribution']['Status'];
        }

        if (isset($result['@metadata']['effectiveUri'])) {
            $message .= ', and the effective URI is ' .
                $result['@metadata']['effectiveUri'] . '.';
        } else {
            $message = 'Error: Could not get the specified distribution. ' .
                'The distribution\'s status is not available.';
        }

        return $message;
    } catch (AwsException $e) {
        return 'Error: ' . $e->getAwsErrorMessage();
    }
}

function getsADistribution()
{
    $distributionId = 'E1BTGP2EXAMPLE';

    $cloudFrontClient = new Aws\CloudFront\CloudFrontClient([
        'profile' => 'default',
        'version' => '2018-06-18',
        'region' => 'us-east-1'
    ]);

    echo getDistribution($cloudFrontClient, $distributionId);
}

// Uncomment the following line to run this code in an AWS account.
// getsADistribution();
```

## 列出 CloudFront 分配
<a name="list-cf-distributions"></a>

使用 [ListDistributions](https://docs.aws.amazon.com/cloudfront/latest/APIReference/API_ListDistributions.html) 操作，从您的当前账户中获取指定 AWS 区域中现有 CloudFront 分配的列表。

 **导入**。

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

use Aws\Exception\AwsException;
```

 **示例代码** 

```
function listDistributions($cloudFrontClient)
{
    try {
        $result = $cloudFrontClient->listDistributions([]);
        return $result;
    } catch (AwsException $e) {
        exit('Error: ' . $e->getAwsErrorMessage());
    }
}

function listTheDistributions()
{
    $cloudFrontClient = new Aws\CloudFront\CloudFrontClient([
        'profile' => 'default',
        'version' => '2018-06-18',
        'region' => 'us-east-2'
    ]);

    $distributions = listDistributions($cloudFrontClient);

    if (count($distributions) == 0) {
        echo 'Could not find any distributions.';
    } else {
        foreach ($distributions['DistributionList']['Items'] as $distribution) {
            echo 'The distribution with the ID of ' . $distribution['Id'] .
                ' has the status of ' . $distribution['Status'] . '.' . "\n";
        }
    }
}

// Uncomment the following line to run this code in an AWS account.
// listTheDistributions();
```

## 更新 CloudFront 分配
<a name="update-a-cf-distribution"></a>

更新 CloudFront 分配的操作与创建分配的操作类似。但是，当您更新分配时，更多字段都是必填字段且必须包含所有值。要对现有分配进行更改，我们建议您首先检索现有分配，然后更新您要在 `$distribution` 数组中更改的值。

要更新指定的 CloudFront 分配，请使用 [UpdateDistribution](https://docs.aws.amazon.com/cloudfront/latest/APIReference/API_UpdateDistribution.html) 操作。

 **导入**。

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

use Aws\CloudFront\CloudFrontClient;
use Aws\Exception\AwsException;
```

 **示例代码** 

```
function updateDistribution(
    $cloudFrontClient,
    $distributionId,
    $distributionConfig,
    $eTag
) {
    try {
        $result = $cloudFrontClient->updateDistribution([
            'DistributionConfig' => $distributionConfig,
            'Id' => $distributionId,
            'IfMatch' => $eTag
        ]);

        return 'The distribution with the following effective URI has ' .
            'been updated: ' . $result['@metadata']['effectiveUri'];
    } catch (AwsException $e) {
        return 'Error: ' . $e->getAwsErrorMessage();
    }
}

function getDistributionConfig($cloudFrontClient, $distributionId)
{
    try {
        $result = $cloudFrontClient->getDistribution([
            'Id' => $distributionId,
        ]);

        if (isset($result['Distribution']['DistributionConfig'])) {
            return [
                'DistributionConfig' => $result['Distribution']['DistributionConfig'],
                'effectiveUri' => $result['@metadata']['effectiveUri']
            ];
        } else {
            return [
                'Error' => 'Error: Cannot find distribution configuration details.',
                'effectiveUri' => $result['@metadata']['effectiveUri']
            ];
        }
    } catch (AwsException $e) {
        return [
            'Error' => 'Error: ' . $e->getAwsErrorMessage()
        ];
    }
}

function getDistributionETag($cloudFrontClient, $distributionId)
{
    try {
        $result = $cloudFrontClient->getDistribution([
            'Id' => $distributionId,
        ]);

        if (isset($result['ETag'])) {
            return [
                'ETag' => $result['ETag'],
                'effectiveUri' => $result['@metadata']['effectiveUri']
            ];
        } else {
            return [
                'Error' => 'Error: Cannot find distribution ETag header value.',
                'effectiveUri' => $result['@metadata']['effectiveUri']
            ];
        }
    } catch (AwsException $e) {
        return [
            'Error' => 'Error: ' . $e->getAwsErrorMessage()
        ];
    }
}

function updateADistribution()
{
    // $distributionId = 'E1BTGP2EXAMPLE';
    $distributionId = 'E1X3BKQ569KEMH';

    $cloudFrontClient = new CloudFrontClient([
        'profile' => 'default',
        'version' => '2018-06-18',
        'region' => 'us-east-1'
    ]);

    // To change a distribution, you must first get the distribution's
    // ETag header value.
    $eTag = getDistributionETag($cloudFrontClient, $distributionId);

    if (array_key_exists('Error', $eTag)) {
        exit($eTag['Error']);
    }

    // To change a distribution, you must also first get information about
    // the distribution's current configuration. Then you must use that
    // information to build a new configuration.
    $currentConfig = getDistributionConfig($cloudFrontClient, $distributionId);

    if (array_key_exists('Error', $currentConfig)) {
        exit($currentConfig['Error']);
    }

    // To change a distribution's configuration, you can set the
    // distribution's related configuration value as part of a change request,
    // for example:
    // 'Enabled' => true
    // Some configuration values are required to be specified as part of a change
    // request, even if you don't plan to change their values. For ones you
    // don't want to change but are required to be specified, you can just reuse
    // their current values, as follows.
    $distributionConfig = [
        'CallerReference' => $currentConfig['DistributionConfig']["CallerReference"],
        'Comment' => $currentConfig['DistributionConfig']["Comment"],
        'DefaultCacheBehavior' => $currentConfig['DistributionConfig']["DefaultCacheBehavior"],
        'DefaultRootObject' => $currentConfig['DistributionConfig']["DefaultRootObject"],
        'Enabled' => $currentConfig['DistributionConfig']["Enabled"],
        'Origins' => $currentConfig['DistributionConfig']["Origins"],
        'Aliases' => $currentConfig['DistributionConfig']["Aliases"],
        'CustomErrorResponses' => $currentConfig['DistributionConfig']["CustomErrorResponses"],
        'HttpVersion' => $currentConfig['DistributionConfig']["HttpVersion"],
        'CacheBehaviors' => $currentConfig['DistributionConfig']["CacheBehaviors"],
        'Logging' => $currentConfig['DistributionConfig']["Logging"],
        'PriceClass' => $currentConfig['DistributionConfig']["PriceClass"],
        'Restrictions' => $currentConfig['DistributionConfig']["Restrictions"],
        'ViewerCertificate' => $currentConfig['DistributionConfig']["ViewerCertificate"],
        'WebACLId' => $currentConfig['DistributionConfig']["WebACLId"]
    ];

    echo updateDistribution(
        $cloudFrontClient,
        $distributionId,
        $distributionConfig,
        $eTag['ETag']
    );
}

// Uncomment the following line to run this code in an AWS account.
// updateADistribution();
```

## 禁用 CloudFront 分配
<a name="disable-a-cf-distribution"></a>

要停用或删除分配，请将其状态从“已部署”更改为“已禁用”。

要禁用指定的 CloudFront 分配，请使用 [DisableDistribution](https://docs.aws.amazon.com/cloudfront/latest/APIReference/API_DisableDistribution.html) 操作。

 **导入**。

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

use Aws\Exception\AwsException;
```

 **示例代码** 

```
function disableDistribution(
    $cloudFrontClient,
    $distributionId,
    $distributionConfig,
    $eTag
) {
    try {
        $result = $cloudFrontClient->updateDistribution([
            'DistributionConfig' => $distributionConfig,
            'Id' => $distributionId,
            'IfMatch' => $eTag
        ]);
        return 'The distribution with the following effective URI has ' .
            'been disabled: ' . $result['@metadata']['effectiveUri'];
    } catch (AwsException $e) {
        return 'Error: ' . $e->getAwsErrorMessage();
    }
}

function getDistributionConfig($cloudFrontClient, $distributionId)
{
    try {
        $result = $cloudFrontClient->getDistribution([
            'Id' => $distributionId,
        ]);

        if (isset($result['Distribution']['DistributionConfig'])) {
            return [
                'DistributionConfig' => $result['Distribution']['DistributionConfig'],
                'effectiveUri' => $result['@metadata']['effectiveUri']
            ];
        } else {
            return [
                'Error' => 'Error: Cannot find distribution configuration details.',
                'effectiveUri' => $result['@metadata']['effectiveUri']
            ];
        }
    } catch (AwsException $e) {
        return [
            'Error' => 'Error: ' . $e->getAwsErrorMessage()
        ];
    }
}

function getDistributionETag($cloudFrontClient, $distributionId)
{
    try {
        $result = $cloudFrontClient->getDistribution([
            'Id' => $distributionId,
        ]);

        if (isset($result['ETag'])) {
            return [
                'ETag' => $result['ETag'],
                'effectiveUri' => $result['@metadata']['effectiveUri']
            ];
        } else {
            return [
                'Error' => 'Error: Cannot find distribution ETag header value.',
                'effectiveUri' => $result['@metadata']['effectiveUri']
            ];
        }
    } catch (AwsException $e) {
        return [
            'Error' => 'Error: ' . $e->getAwsErrorMessage()
        ];
    }
}

function disableADistribution()
{
    $distributionId = 'E1BTGP2EXAMPLE';

    $cloudFrontClient = new Aws\CloudFront\CloudFrontClient([
        'profile' => 'default',
        'version' => '2018-06-18',
        'region' => 'us-east-1'
    ]);

    // To disable a distribution, you must first get the distribution's
    // ETag header value.
    $eTag = getDistributionETag($cloudFrontClient, $distributionId);

    if (array_key_exists('Error', $eTag)) {
        exit($eTag['Error']);
    }

    // To delete a distribution, you must also first get information about
    // the distribution's current configuration. Then you must use that
    // information to build a new configuration, including setting the new
    // configuration to "disabled".
    $currentConfig = getDistributionConfig($cloudFrontClient, $distributionId);

    if (array_key_exists('Error', $currentConfig)) {
        exit($currentConfig['Error']);
    }

    $distributionConfig = [
        'CacheBehaviors' => $currentConfig['DistributionConfig']["CacheBehaviors"],
        'CallerReference' => $currentConfig['DistributionConfig']["CallerReference"],
        'Comment' => $currentConfig['DistributionConfig']["Comment"],
        'DefaultCacheBehavior' => $currentConfig['DistributionConfig']["DefaultCacheBehavior"],
        'DefaultRootObject' => $currentConfig['DistributionConfig']["DefaultRootObject"],
        'Enabled' => false,
        'Origins' => $currentConfig['DistributionConfig']["Origins"],
        'Aliases' => $currentConfig['DistributionConfig']["Aliases"],
        'CustomErrorResponses' => $currentConfig['DistributionConfig']["CustomErrorResponses"],
        'HttpVersion' => $currentConfig['DistributionConfig']["HttpVersion"],
        'Logging' => $currentConfig['DistributionConfig']["Logging"],
        'PriceClass' => $currentConfig['DistributionConfig']["PriceClass"],
        'Restrictions' => $currentConfig['DistributionConfig']["Restrictions"],
        'ViewerCertificate' => $currentConfig['DistributionConfig']["ViewerCertificate"],
        'WebACLId' => $currentConfig['DistributionConfig']["WebACLId"]
    ];

    echo disableDistribution(
        $cloudFrontClient,
        $distributionId,
        $distributionConfig,
        $eTag['ETag']
    );
}

// Uncomment the following line to run this code in an AWS account.
// disableADistribution();
```

## 删除 CloudFront 分配
<a name="delete-a-cf-distribution"></a>

一旦分配处于已禁用状态，您即可删除分配。

要删除指定的 CloudFront 分配，请使用 [DeleteDistribution](https://docs.aws.amazon.com/cloudfront/latest/APIReference/API_DeleteDistribution.html) 操作。

 **导入**。

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

use Aws\Exception\AwsException;
```

 **示例代码** 

```
function deleteDistribution($cloudFrontClient, $distributionId, $eTag)
{
    try {
        $result = $cloudFrontClient->deleteDistribution([
            'Id' => $distributionId,
            'IfMatch' => $eTag
        ]);
        return 'The distribution at the following effective URI has ' .
            'been deleted: ' . $result['@metadata']['effectiveUri'];
    } catch (AwsException $e) {
        return 'Error: ' . $e->getAwsErrorMessage();
    }
}

function getDistributionETag($cloudFrontClient, $distributionId)
{
    try {
        $result = $cloudFrontClient->getDistribution([
            'Id' => $distributionId,
        ]);

        if (isset($result['ETag'])) {
            return [
                'ETag' => $result['ETag'],
                'effectiveUri' => $result['@metadata']['effectiveUri']
            ];
        } else {
            return [
                'Error' => 'Error: Cannot find distribution ETag header value.',
                'effectiveUri' => $result['@metadata']['effectiveUri']
            ];
        }
    } catch (AwsException $e) {
        return [
            'Error' => 'Error: ' . $e->getAwsErrorMessage()
        ];
    }
}

function deleteADistribution()
{
    $distributionId = 'E17G7YNEXAMPLE';

    $cloudFrontClient = new Aws\CloudFront\CloudFrontClient([
        'profile' => 'default',
        'version' => '2018-06-18',
        'region' => 'us-east-1'
    ]);

    // To delete a distribution, you must first get the distribution's
    // ETag header value.
    $eTag = getDistributionETag($cloudFrontClient, $distributionId);

    if (array_key_exists('Error', $eTag)) {
        exit($eTag['Error']);
    } else {
        echo deleteDistribution(
            $cloudFrontClient,
            $distributionId,
            $eTag['ETag']
        );
    }
}

// Uncomment the following line to run this code in an AWS account.
// deleteADistribution();
```

# 使用 CloudFront API 和 适用于 PHP 的 AWS SDK 版本 3 来管理 Amazon CloudFront 失效
<a name="cloudfront-example-invalidation"></a>

Amazon CloudFront 将静态和动态文件的副本缓存在全球边缘站点中。要在所有边缘站点上删除或更新文件，请为每个文件或一组文件创建失效。

每个日历月中，您的前 1,000 个失效是免费的。要了解有关从 CloudFront 边缘站点删除内容的更多信息，请参阅[使文件失效](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/Invalidation.html)。

以下示例演示如何：
+ 使用 [CreateInvalidation](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-cloudfront-2018-11-05.html#createinvalidation) 创建分配失效。
+ 使用 [GetInvalidation](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-cloudfront-2018-11-05.html#getinvalidation) 获取分配失效。
+ 使用 [ListInvalidations](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-cloudfront-2018-11-05.html#listinvalidations) 列出分配失效。

适用于 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) 中所述。

有关使用 Amazon CloudFront 的更多信息，请参阅 [Amazon CloudFront 开发人员指南](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/)。

## 创建分配失效
<a name="create-a-distribution-invalidation"></a>

通过指定需要删除的文件的路径位置来创建 CloudFront 分配失效。此示例将使分配中的所有文件均失效，但您可以在 `Items` 下标识特定文件。

要创建 CloudFront 分配失效，请使用 [CreateInvalidation](https://docs.aws.amazon.com/cloudfront/latest/APIReference/API_CreateInvalidation.html) 操作。

 **导入**。

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

use Aws\Exception\AwsException;
```

 **示例代码** 

```
function createInvalidation(
    $cloudFrontClient,
    $distributionId,
    $callerReference,
    $paths,
    $quantity
) {
    try {
        $result = $cloudFrontClient->createInvalidation([
            'DistributionId' => $distributionId,
            'InvalidationBatch' => [
                'CallerReference' => $callerReference,
                'Paths' => [
                    'Items' => $paths,
                    'Quantity' => $quantity,
                ],
            ]
        ]);

        $message = '';

        if (isset($result['Location'])) {
            $message = 'The invalidation location is: ' . $result['Location'];
        }

        $message .= ' and the effective URI is ' . $result['@metadata']['effectiveUri'] . '.';

        return $message;
    } catch (AwsException $e) {
        return 'Error: ' . $e->getAwsErrorMessage();
    }
}

function createTheInvalidation()
{
    $distributionId = 'E17G7YNEXAMPLE';
    $callerReference = 'my-unique-value';
    $paths = ['/*'];
    $quantity = 1;

    $cloudFrontClient = new Aws\CloudFront\CloudFrontClient([
        'profile' => 'default',
        'version' => '2018-06-18',
        'region' => 'us-east-1'
    ]);

    echo createInvalidation(
        $cloudFrontClient,
        $distributionId,
        $callerReference,
        $paths,
        $quantity
    );
}

// Uncomment the following line to run this code in an AWS account.
// createTheInvalidation();
```

## 获取分配失效
<a name="get-a-distribution-invalidation"></a>

要检索有关 CloudFront 分配失效的状态和详细信息，请使用 [GetInvalidation](https://docs.aws.amazon.com/cloudfront/latest/APIReference/API_GetInvalidation.html) 操作。

 **导入**。

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

use Aws\Exception\AwsException;
```

 **示例代码** 

```
function getInvalidation($cloudFrontClient, $distributionId, $invalidationId)
{
    try {
        $result = $cloudFrontClient->getInvalidation([
            'DistributionId' => $distributionId,
            'Id' => $invalidationId,
        ]);

        $message = '';

        if (isset($result['Invalidation']['Status'])) {
            $message = 'The status for the invalidation with the ID of ' .
                $result['Invalidation']['Id'] . ' is ' .
                $result['Invalidation']['Status'];
        }

        if (isset($result['@metadata']['effectiveUri'])) {
            $message .= ', and the effective URI is ' .
                $result['@metadata']['effectiveUri'] . '.';
        } else {
            $message = 'Error: Could not get information about ' .
                'the invalidation. The invalidation\'s status ' .
                'was not available.';
        }

        return $message;
    } catch (AwsException $e) {
        return 'Error: ' . $e->getAwsErrorMessage();
    }
}

function getsAnInvalidation()
{
    $distributionId = 'E1BTGP2EXAMPLE';
    $invalidationId = 'I1CDEZZEXAMPLE';

    $cloudFrontClient = new Aws\CloudFront\CloudFrontClient([
        'profile' => 'default',
        'version' => '2018-06-18',
        'region' => 'us-east-1'
    ]);

    echo getInvalidation($cloudFrontClient, $distributionId, $invalidationId);
}

// Uncomment the following line to run this code in an AWS account.
// getsAnInvalidation();
```

## 列出分配失效
<a name="list-distribution-invalidations"></a>

要列出所有当前 CloudFront 分配失效，请使用 [ListInvalidations](https://docs.aws.amazon.com/cloudfront/latest/APIReference/API_ListInvalidations.html) 操作。

 **导入**。

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

use Aws\Exception\AwsException;
```

 **示例代码** 

```
function listInvalidations($cloudFrontClient, $distributionId)
{
    try {
        $result = $cloudFrontClient->listInvalidations([
            'DistributionId' => $distributionId
        ]);
        return $result;
    } catch (AwsException $e) {
        exit('Error: ' . $e->getAwsErrorMessage());
    }
}

function listTheInvalidations()
{
    $distributionId = 'E1WICG1EXAMPLE';

    $cloudFrontClient = new Aws\CloudFront\CloudFrontClient([
        'profile' => 'default',
        'version' => '2018-06-18',
        'region' => 'us-east-1'
    ]);

    $invalidations = listInvalidations(
        $cloudFrontClient,
        $distributionId
    );

    if (isset($invalidations['InvalidationList'])) {
        if ($invalidations['InvalidationList']['Quantity'] > 0) {
            foreach ($invalidations['InvalidationList']['Items'] as $invalidation) {
                echo 'The invalidation with the ID of ' . $invalidation['Id'] .
                    ' has the status of ' . $invalidation['Status'] . '.' . "\n";
            }
        } else {
            echo 'Could not find any invalidations for the specified distribution.';
        }
    } else {
        echo 'Error: Could not get invalidation information. Could not get ' .
            'information about the specified distribution.';
    }
}

// Uncomment the following line to run this code in an AWS account.
// listTheInvalidations();
```

# CloudFront URLs 使用 适用于 PHP 的 AWS SDK 版本 3 签署亚马逊
<a name="cloudfront-example-signed-url"></a>

 URLs 通过签名，您可以向用户提供访问您的私有内容的权限。签名 URL 中包含的其他信息（例如，到期时间）可让您更好地控制对内容的访问。该额外信息出现在策略声明中，且是基于标准策略或自定义策略。有关如何设置私有分配以及为什么需要签署的信息 URLs，请参阅《亚马逊 CloudFront 开发者指南》 CloudFront中的[通过亚马逊提供私有内容](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/PrivateContent.html)。
+ 使用 [getSigne](https://docs.aws.amazon.com/aws-sdk-php/v3/api/class-Aws.CloudFront.CloudFrontClient.html#_getSignedUrl) Durl 创建已签名的亚马逊 CloudFront URL。
+ 使用创建已签名的亚马逊 CloudFront Cookie [getSignedCookie](https://docs.aws.amazon.com/aws-sdk-php/v3/api/class-Aws.CloudFront.CloudFrontClient.html#_getSignedCookie)。

的所有示例代码都可以在[此 适用于 PHP 的 AWS SDK 处找到 GitHub](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)。

有关使用亚马逊的更多信息 CloudFront，请参阅[亚马逊 CloudFront 开发者指南](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/)。

## 签署私 CloudFront URLs 有发行版
<a name="signing-cf-urls-for-private-distributions"></a>

您可以使用 SDK 中的 CloudFront 客户端对 URL 进行签名。首先，您必须创建一个 `CloudFrontClient` 对象。您可以使用固定政策或自定义政策为视频资源签名 CloudFront URL。

 **导入** 

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

use Aws\CloudFront\CloudFrontClient;
use Aws\Exception\AwsException;
```

 **示例代码** 

```
function signPrivateDistribution(
    $cloudFrontClient,
    $resourceKey,
    $expires,
    $privateKey,
    $keyPairId
) {
    try {
        $result = $cloudFrontClient->getSignedUrl([
            'url' => $resourceKey,
            'expires' => $expires,
            'private_key' => $privateKey,
            'key_pair_id' => $keyPairId
        ]);

        return $result;
    } catch (AwsException $e) {
        return 'Error: ' . $e->getAwsErrorMessage();
    }
}

function signAPrivateDistribution()
{
    $resourceKey = 'https://d13l49jEXAMPLE.cloudfront.net/my-file.txt';
    $expires = time() + 300; // 5 minutes (5 * 60 seconds) from now.
    $privateKey = dirname(__DIR__) . '/cloudfront/my-private-key.pem';
    $keyPairId = 'AAPKAJIKZATYYYEXAMPLE';

    $cloudFrontClient = new CloudFrontClient([
        'profile' => 'default',
        'version' => '2018-06-18',
        'region' => 'us-east-1'
    ]);

    echo signPrivateDistribution(
        $cloudFrontClient,
        $resourceKey,
        $expires,
        $privateKey,
        $keyPairId
    );
}

// Uncomment the following line to run this code in an AWS account.
// signAPrivateDistribution();
```

## 创建时使用自定义策略 CloudFront URLs
<a name="use-a-custom-policy-when-creating-cf-urls"></a>

要使用自定义策略，请提供 `policy` 键，而不是 `expires`。

 **导入** 

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

use Aws\CloudFront\CloudFrontClient;
use Aws\Exception\AwsException;
```

 **示例代码** 

```
function signPrivateDistributionPolicy(
    $cloudFrontClient,
    $resourceKey,
    $customPolicy,
    $privateKey,
    $keyPairId
) {
    try {
        $result = $cloudFrontClient->getSignedUrl([
            'url' => $resourceKey,
            'policy' => $customPolicy,
            'private_key' => $privateKey,
            'key_pair_id' => $keyPairId
        ]);

        return $result;
    } catch (AwsException $e) {
        return 'Error: ' . $e->getAwsErrorMessage();
    }
}

function signAPrivateDistributionPolicy()
{
    $resourceKey = 'https://d13l49jEXAMPLE.cloudfront.net/my-file.txt';
    $expires = time() + 300; // 5 minutes (5 * 60 seconds) from now.
    $customPolicy = <<<POLICY
{
    "Statement": [
        {
            "Resource": "$resourceKey",
            "Condition": {
                "IpAddress": {"AWS:SourceIp": "{$_SERVER['REMOTE_ADDR']}/32"},
                "DateLessThan": {"AWS:EpochTime": $expires}
            }
        }
    ]
}
POLICY;
    $privateKey = dirname(__DIR__) . '/cloudfront/my-private-key.pem';
    $keyPairId = 'AAPKAJIKZATYYYEXAMPLE';

    $cloudFrontClient = new CloudFrontClient([
        'profile' => 'default',
        'version' => '2018-06-18',
        'region' => 'us-east-1'
    ]);

    echo signPrivateDistributionPolicy(
        $cloudFrontClient,
        $resourceKey,
        $customPolicy,
        $privateKey,
        $keyPairId
    );
}

// Uncomment the following line to run this code in an AWS account.
// signAPrivateDistributionPolicy();
```

## 使用 CloudFront 签名网址
<a name="use-a-cf-signed-url"></a>

根据您要签名的 URL 使用的是“HTTP”还是“RTMP”方案，签名后的 URL 的形式将有所不同。如果是“HTTP”方案，将返回完整的绝对 URL。如果是“RTMP”方案，则为了方便起见，只会返回相对 URL。这是因为某些播放器要求分别提供主机和路径参数。

以下示例说明如何使用签名 URL 来构造显示视频的网页[JWPlayer](http://www.longtailvideo.com/jw-player/)。相同类型的技术也适用于其他玩家 [FlowPlayer](http://flowplayer.org/)，例如，但需要不同的客户端代码。

```
<html>
<head>
    <title>|CFlong| Streaming Example</title>
    <script type="text/javascript" src="https://example.com/jwplayer.js"></script>
</head>
<body>
    <div id="video">The canned policy video will be here.</div>
    <script type="text/javascript">
        jwplayer('video').setup({
            file: "<?= $streamHostUrl ?>/cfx/st/<?= $signedUrlCannedPolicy ?>",
            width: "720",
            height: "480"
        });
    </script>
</body>
</html>
```

## 为私人分发签名 CloudFront Cookie
<a name="signing-cf-cookies-for-private-distributions"></a>

作为已签名的替代方案 URLs，您还可以通过签名 Cookie 向客户授予访问私有分发的权限。借助经过签名的 Cookie，您可以提供对多个受限文件的访问权限，例如 HLS 格式视频的所有文件，或在网站订阅者区域中的所有文件。要详细了解为何要使用签名 Cookie 而不是签名 URLs （反之亦然），请参阅《亚马逊 CloudFront 开发者指南》中的在[签名 Cookie URLs 和签名 Cookie 之间进行选择](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/private-content-choosing-signed-urls-cookies.html)。

创建签名 cookie 的方法与创建签名 URL 的方法类似。唯一的区别是调用的方法（`getSignedCookie`，而不是 `getSignedUrl`）。

 **导入** 

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

use Aws\CloudFront\CloudFrontClient;
use Aws\Exception\AwsException;
```

 **示例代码** 

```
function signCookie(
    $cloudFrontClient,
    $resourceKey,
    $expires,
    $privateKey,
    $keyPairId
) {
    try {
        $result = $cloudFrontClient->getSignedCookie([
            'url' => $resourceKey,
            'expires' => $expires,
            'private_key' => $privateKey,
            'key_pair_id' => $keyPairId
        ]);

        return $result;
    } catch (AwsException $e) {
        return [ 'Error' => $e->getAwsErrorMessage() ];
    }
}

function signACookie()
{
    $resourceKey = 'https://d13l49jEXAMPLE.cloudfront.net/my-file.txt';
    $expires = time() + 300; // 5 minutes (5 * 60 seconds) from now.
    $privateKey = dirname(__DIR__) . '/cloudfront/my-private-key.pem';
    $keyPairId = 'AAPKAJIKZATYYYEXAMPLE';

    $cloudFrontClient = new CloudFrontClient([
        'profile' => 'default',
        'version' => '2018-06-18',
        'region' => 'us-east-1'
    ]);

    $result = signCookie(
        $cloudFrontClient,
        $resourceKey,
        $expires,
        $privateKey,
        $keyPairId
    );

    /* If successful, returns something like:
    CloudFront-Expires = 1589926678
    CloudFront-Signature = Lv1DyC2q...2HPXaQ__
    CloudFront-Key-Pair-Id = AAPKAJIKZATYYYEXAMPLE
    */
    foreach ($result as $key => $value) {
        echo $key . ' = ' . $value . "\n";
    }
}

// Uncomment the following line to run this code in an AWS account.
// signACookie();
```

## 创建 CloudFront Cookie 时使用自定义策略
<a name="use-a-custom-policy-when-creating-cf-cookies"></a>

与 `getSignedUrl` 相同，您可以提供 `'policy'` 参数（而不是 `expires` 参数），以及 `url` 参数，使用自定义策略针对 Cookie 签名。自定义策略可以在资源键中包含通配符。这样您就可以为多个文件创建一个签名 Cookie。

 `getSignedCookie` 返回的键值对数组均需设置为 Cookie，这样才能为私有分配授予访问权限。

 **导入** 

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

use Aws\CloudFront\CloudFrontClient;
use Aws\Exception\AwsException;
```

 **示例代码** 

```
function signCookiePolicy(
    $cloudFrontClient,
    $customPolicy,
    $privateKey,
    $keyPairId
) {
    try {
        $result = $cloudFrontClient->getSignedCookie([
            'policy' => $customPolicy,
            'private_key' => $privateKey,
            'key_pair_id' => $keyPairId
        ]);

        return $result;
    } catch (AwsException $e) {
        return [ 'Error' => $e->getAwsErrorMessage() ];
    }
}

function signACookiePolicy()
{
    $resourceKey = 'https://d13l49jEXAMPLE.cloudfront.net/my-file.txt';
    $expires = time() + 300; // 5 minutes (5 * 60 seconds) from now.
    $customPolicy = <<<POLICY
{
    "Statement": [
        {
            "Resource": "{$resourceKey}",
            "Condition": {
                "IpAddress": {"AWS:SourceIp": "{$_SERVER['REMOTE_ADDR']}/32"},
                "DateLessThan": {"AWS:EpochTime": {$expires}}
            }
        }
    ]
}
POLICY;
    $privateKey = dirname(__DIR__) . '/cloudfront/my-private-key.pem';
    $keyPairId = 'AAPKAJIKZATYYYEXAMPLE';

    $cloudFrontClient = new CloudFrontClient([
        'profile' => 'default',
        'version' => '2018-06-18',
        'region' => 'us-east-1'
    ]);

    $result = signCookiePolicy(
        $cloudFrontClient,
        $customPolicy,
        $privateKey,
        $keyPairId
    );

    /* If successful, returns something like:
    CloudFront-Policy = eyJTdGF0...fX19XX0_
    CloudFront-Signature = RowqEQWZ...N8vetw__
    CloudFront-Key-Pair-Id = AAPKAJIKZATYYYEXAMPLE
    */
    foreach ($result as $key => $value) {
        echo $key . ' = ' . $value . "\n";
    }
}

// Uncomment the following line to run this code in an AWS account.
// signACookiePolicy();
```

## 向 Guzzle 客户端发送 CloudFront cookie
<a name="send-cf-cookies-to-guzzle-client"></a>

您也可以将这些 Cookie 传递至 `GuzzleHttp\Cookie\CookieJar`，与 Guzzle 客户端结合使用。

```
use GuzzleHttp\Client;
use GuzzleHttp\Cookie\CookieJar;

$distribution = "example-distribution.cloudfront.net";
$client = new \GuzzleHttp\Client([
    'base_uri' => "https://$distribution",
    'cookies' => CookieJar::fromArray($signedCookieCustomPolicy, $distribution),
]);

$client->get('video.mp4');
```

有关更多信息，请参阅《亚马逊 CloudFront 开发者指南》中的[使用签名 Cookie](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/private-content-signed-cookies.html)。

# 使用 适用于 PHP 的 AWS SDK 版本 3 来针对自定义 Amazon CloudSearch 域请求签名
<a name="service_cloudsearch-custom-requests"></a>

可以在 适用于 PHP 的 AWS SDK 支持的范围之外对 Amazon CloudSearch 域请求进行自定义。当您需要向受 IAM 身份验证保护的域发出自定义请求时，可以使用 SDK 的凭证提供程序和签署人对任何 [PSR-7 请求](https://docs.aws.amazon.com/aws-sdk-php/v3/api/class-Psr.Http.Message.RequestInterface.html)签名。

例如，如果您要按照 [Cloud Search 的入门指南](https://docs.aws.amazon.com/cloudsearch/latest/developerguide/getting-started.html)操作，并想在[第 3 步](https://docs.aws.amazon.com/cloudsearch/latest/developerguide/getting-started-search.html)中使用受 IAM 保护的域，则需要按以下方式签署并执行请求。

以下示例演示如何：
+ 使用 [SignatureV4](https://docs.aws.amazon.com/aws-sdk-php/v3/api/class-Aws.Signature.SignatureV4.html#_signRequest) 通过 AWS 签名协议签署请求。

适用于 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) 中所述。

## 签署 Amazon CloudSearch 域请求
<a name="sign-cslong-domain-request"></a>

 **导入**。

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

use Aws\Credentials\CredentialProvider;
use Aws\Signature\SignatureV4;
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Request;
```

 **示例代码** 

```
function searchDomain(
    $client,
    $domainName,
    $domainId,
    $domainRegion,
    $searchString
) {
    $domainPrefix = 'search-';
    $cloudSearchDomain = 'cloudsearch.amazonaws.com';
    $cloudSearchVersion = '2013-01-01';
    $searchPrefix = 'search?';

    // Specify the search to send.
    $request = new Request(
        'GET',
        "https://$domainPrefix$domainName-$domainId.$domainRegion." .
            "$cloudSearchDomain/$cloudSearchVersion/" .
            "$searchPrefix$searchString"
    );

    // Get default AWS account access credentials.
    $credentials = call_user_func(CredentialProvider::defaultProvider())->wait();

    // Sign the search request with the credentials.
    $signer = new SignatureV4('cloudsearch', $domainRegion);
    $request = $signer->signRequest($request, $credentials);

    // Send the signed search request.
    $response = $client->send($request);

    // Report the search results, if any.
    $results = json_decode($response->getBody());

    $message = '';

    if ($results->hits->found > 0) {
        $message .= 'Search results:' . "\n";

        foreach ($results->hits->hit as $hit) {
            $message .= $hit->fields->title . "\n";
        }
    } else {
        $message .= 'No search results.';
    }

    return $message;
}

function searchADomain()
{
    $domainName = 'my-search-domain';
    $domainId = '7kbitd6nyiglhdtmssxEXAMPLE';
    $domainRegion = 'us-east-1';
    $searchString = 'q=star+wars&return=title';
    $client = new Client();

    echo searchDomain(
        $client,
        $domainName,
        $domainId,
        $domainRegion,
        $searchString
    );
}

// Uncomment the following line to run this code in an AWS account.
// searchADomain();
```

# 使用 适用于 PHP 的 AWS SDK 版本 3 的 Amazon CloudWatch 示例
<a name="cw-examples"></a>

Amazon CloudWatch (CloudWatch) 是一项 Web 服务，可实时监控您的 Amazon Web Services 资源以及您在 AWS 上运行的应用程序。您可以使用 CloudWatch 收集和跟踪指标，这些指标是您可衡量的相关资源和应用程序的变量。CloudWatch 警报可根据您定义的规则发送通知或者对您所监控的资源自动进行更改。

适用于 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) 中所述。

**Topics**
+ [凭证](#examplecredentials)
+ [使用 Amazon CloudWatch 警报](cw-examples-work-with-alarms.md)
+ [从 CloudWatch 获取指标](cw-examples-getting-metrics.md)
+ [在 Amazon CloudWatch 中发布自定义指标](cw-examples-publishing-custom-metrics.md)
+ [向 Amazon CloudWatch 活动发送事件](cw-examples-sending-events.md)
+ [将警报操作用于 Amazon CloudWatch 警报](cw-examples-using-alarm-actions.md)

# 使用 适用于 PHP 的 AWS SDK 版本 3 来使用 Amazon CloudWatch 警报
<a name="cw-examples-work-with-alarms"></a>

Amazon CloudWatch 警报在指定时间段内监控某个指标。它在多个时间段内根据相对于给定阈值的指标值，执行一项或多项操作。

以下示例演示如何：
+ 使用 [DescribeAlarms](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-monitoring-2010-08-01.html#describealarms) 描述警报。
+ 使用 [PutMetricAlarm](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-monitoring-2010-08-01.html#putmetricalarm) 创建警报。
+ 使用 [DeleteAlarms](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-monitoring-2010-08-01.html#deletealarms) 删除警报。

适用于 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) 中所述。

## 描述警报
<a name="describe-alarms"></a>

 **导入**。

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

use Aws\CloudWatch\CloudWatchClient;
use Aws\Exception\AwsException;
```

 **示例代码** 

```
function describeAlarms($cloudWatchClient)
{
    try {
        $result = $cloudWatchClient->describeAlarms();

        $message = '';

        if (isset($result['@metadata']['effectiveUri'])) {
            $message .= 'Alarms at the effective URI of ' .
                $result['@metadata']['effectiveUri'] . "\n\n";

            if (isset($result['CompositeAlarms'])) {
                $message .= "Composite alarms:\n";

                foreach ($result['CompositeAlarms'] as $alarm) {
                    $message .= $alarm['AlarmName'] . "\n";
                }
            } else {
                $message .= "No composite alarms found.\n";
            }

            if (isset($result['MetricAlarms'])) {
                $message .= "Metric alarms:\n";

                foreach ($result['MetricAlarms'] as $alarm) {
                    $message .= $alarm['AlarmName'] . "\n";
                }
            } else {
                $message .= 'No metric alarms found.';
            }
        } else {
            $message .= 'No alarms found.';
        }

        return $message;
    } catch (AwsException $e) {
        return 'Error: ' . $e->getAwsErrorMessage();
    }
}

function describeTheAlarms()
{
    $cloudWatchClient = new CloudWatchClient([
        'profile' => 'default',
        'region' => 'us-east-1',
        'version' => '2010-08-01'
    ]);

    echo describeAlarms($cloudWatchClient);
}

// Uncomment the following line to run this code in an AWS account.
// describeTheAlarms();
```

## 创建警报
<a name="create-an-alarm"></a>

 **导入**。

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

use Aws\CloudWatch\CloudWatchClient;
use Aws\Exception\AwsException;
```

 **示例代码** 

```
function putMetricAlarm(
    $cloudWatchClient,
    $cloudWatchRegion,
    $alarmName,
    $namespace,
    $metricName,
    $dimensions,
    $statistic,
    $period,
    $comparison,
    $threshold,
    $evaluationPeriods
) {
    try {
        $result = $cloudWatchClient->putMetricAlarm([
            'AlarmName' => $alarmName,
            'Namespace' => $namespace,
            'MetricName' => $metricName,
            'Dimensions' => $dimensions,
            'Statistic' => $statistic,
            'Period' => $period,
            'ComparisonOperator' => $comparison,
            'Threshold' => $threshold,
            'EvaluationPeriods' => $evaluationPeriods
        ]);

        if (isset($result['@metadata']['effectiveUri'])) {
            if (
                $result['@metadata']['effectiveUri'] ==
                'https://monitoring.' . $cloudWatchRegion . '.amazonaws.com'
            ) {
                return 'Successfully created or updated specified alarm.';
            } else {
                return 'Could not create or update specified alarm.';
            }
        } else {
            return 'Could not create or update specified alarm.';
        }
    } catch (AwsException $e) {
        return 'Error: ' . $e->getAwsErrorMessage();
    }
}

function putTheMetricAlarm()
{
    $alarmName = 'my-ec2-resources';
    $namespace = 'AWS/Usage';
    $metricName = 'ResourceCount';
    $dimensions = [
        [
            'Name' => 'Type',
            'Value' => 'Resource'
        ],
        [
            'Name' => 'Resource',
            'Value' => 'vCPU'
        ],
        [
            'Name' => 'Service',
            'Value' => 'EC2'
        ],
        [
            'Name' => 'Class',
            'Value' => 'Standard/OnDemand'
        ]
    ];
    $statistic = 'Average';
    $period = 300;
    $comparison = 'GreaterThanThreshold';
    $threshold = 1;
    $evaluationPeriods = 1;

    $cloudWatchRegion = 'us-east-1';
    $cloudWatchClient = new CloudWatchClient([
        'profile' => 'default',
        'region' => $cloudWatchRegion,
        'version' => '2010-08-01'
    ]);

    echo putMetricAlarm(
        $cloudWatchClient,
        $cloudWatchRegion,
        $alarmName,
        $namespace,
        $metricName,
        $dimensions,
        $statistic,
        $period,
        $comparison,
        $threshold,
        $evaluationPeriods
    );
}

// Uncomment the following line to run this code in an AWS account.
// putTheMetricAlarm();
```

## 删除警报
<a name="delete-alarms"></a>

 **导入**。

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

use Aws\CloudWatch\CloudWatchClient;
use Aws\Exception\AwsException;
```

 **示例代码** 

```
function deleteAlarms($cloudWatchClient, $alarmNames)
{
    try {
        $result = $cloudWatchClient->deleteAlarms([
            'AlarmNames' => $alarmNames
        ]);

        return 'The specified alarms at the following effective URI have ' .
            'been deleted or do not currently exist: ' .
            $result['@metadata']['effectiveUri'];
    } catch (AwsException $e) {
        return 'Error: ' . $e->getAwsErrorMessage();
    }
}

function deleteTheAlarms()
{
    $alarmNames = array('my-alarm');

    $cloudWatchClient = new CloudWatchClient([
        'profile' => 'default',
        'region' => 'us-east-1',
        'version' => '2010-08-01'
    ]);

    echo deleteAlarms($cloudWatchClient, $alarmNames);
}

// Uncomment the following line to run this code in an AWS account.
// deleteTheAlarms();
```

# 使用 适用于 PHP 的 AWS SDK 版本 3 来从 Amazon CloudWatch 获取指标
<a name="cw-examples-getting-metrics"></a>

指标是关于您的系统性能的数据。您可以启用对某些资源（例如 Amazon EC2 实例）或您自己的应用程序指标的详细监控。

以下示例演示如何：
+ 使用 [ListMetrics](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-monitoring-2010-08-01.html#listmetrics) 列出指标。
+ 使用 [DescribeAlarmsForMetric](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-monitoring-2010-08-01.html#describealarmsformetric) 检索指标的警报。
+ 使用 [GetMetricStatistics](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-monitoring-2010-08-01.html#getmetricstatistics) 获取指定指标的统计数据。

适用于 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) 中所述。

## 列出指标
<a name="list-metrics"></a>

 **导入**。

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

use Aws\CloudWatch\CloudWatchClient;
use Aws\Exception\AwsException;
```

 **示例代码** 

```
function listMetrics($cloudWatchClient)
{
    try {
        $result = $cloudWatchClient->listMetrics();

        $message = '';

        if (isset($result['@metadata']['effectiveUri'])) {
            $message .= 'For the effective URI at ' .
                $result['@metadata']['effectiveUri'] . ":\n\n";

            if (
                (isset($result['Metrics'])) and
                (count($result['Metrics']) > 0)
            ) {
                $message .= "Metrics found:\n\n";

                foreach ($result['Metrics'] as $metric) {
                    $message .= 'For metric ' . $metric['MetricName'] .
                        ' in namespace ' . $metric['Namespace'] . ":\n";

                    if (
                        (isset($metric['Dimensions'])) and
                        (count($metric['Dimensions']) > 0)
                    ) {
                        $message .= "Dimensions:\n";

                        foreach ($metric['Dimensions'] as $dimension) {
                            $message .= 'Name: ' . $dimension['Name'] .
                                ', Value: ' . $dimension['Value'] . "\n";
                        }

                        $message .= "\n";
                    } else {
                        $message .= "No dimensions.\n\n";
                    }
                }
            } else {
                $message .= 'No metrics found.';
            }
        } else {
            $message .= 'No metrics found.';
        }

        return $message;
    } catch (AwsException $e) {
        return 'Error: ' . $e->getAwsErrorMessage();
    }
}

function listTheMetrics()
{
    $cloudWatchClient = new CloudWatchClient([
        'profile' => 'default',
        'region' => 'us-east-1',
        'version' => '2010-08-01'
    ]);

    echo listMetrics($cloudWatchClient);
}

// Uncomment the following line to run this code in an AWS account.
// listTheMetrics();
```

## 检索指标的警报
<a name="retrieve-alarms-for-a-metric"></a>

 **导入**。

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

use Aws\CloudWatch\CloudWatchClient;
use Aws\Exception\AwsException;
```

 **示例代码** 

```
function describeAlarmsForMetric(
    $cloudWatchClient,
    $metricName,
    $namespace,
    $dimensions
) {
    try {
        $result = $cloudWatchClient->describeAlarmsForMetric([
            'MetricName' => $metricName,
            'Namespace' => $namespace,
            'Dimensions' => $dimensions
        ]);

        $message = '';

        if (isset($result['@metadata']['effectiveUri'])) {
            $message .= 'At the effective URI of ' .
                $result['@metadata']['effectiveUri'] . ":\n\n";

            if (
                (isset($result['MetricAlarms'])) and
                (count($result['MetricAlarms']) > 0)
            ) {
                $message .= 'Matching alarms for ' . $metricName . ":\n\n";

                foreach ($result['MetricAlarms'] as $alarm) {
                    $message .= $alarm['AlarmName'] . "\n";
                }
            } else {
                $message .= 'No matching alarms found for ' . $metricName . '.';
            }
        } else {
            $message .= 'No matching alarms found for ' . $metricName . '.';
        }

        return $message;
    } catch (AwsException $e) {
        return 'Error: ' . $e->getAwsErrorMessage();
    }
}

function describeTheAlarmsForMetric()
{
    $metricName = 'BucketSizeBytes';
    $namespace = 'AWS/S3';
    $dimensions = [
        [
            'Name' => 'StorageType',
            'Value' => 'StandardStorage'
        ],
        [
            'Name' => 'BucketName',
            'Value' => 'amzn-s3-demo-bucket'
        ]
    ];

    $cloudWatchClient = new CloudWatchClient([
        'profile' => 'default',
        'region' => 'us-east-1',
        'version' => '2010-08-01'
    ]);

    echo describeAlarmsForMetric(
        $cloudWatchClient,
        $metricName,
        $namespace,
        $dimensions
    );
}

// Uncomment the following line to run this code in an AWS account.
// describeTheAlarmsForMetric();
```

## 获取指标统计数据
<a name="get-metric-statistics"></a>

 **导入**。

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

use Aws\CloudWatch\CloudWatchClient;
use Aws\Exception\AwsException;
```

 **示例代码** 

```
function getMetricStatistics(
    $cloudWatchClient,
    $namespace,
    $metricName,
    $dimensions,
    $startTime,
    $endTime,
    $period,
    $statistics,
    $unit
) {
    try {
        $result = $cloudWatchClient->getMetricStatistics([
            'Namespace' => $namespace,
            'MetricName' => $metricName,
            'Dimensions' => $dimensions,
            'StartTime' => $startTime,
            'EndTime' => $endTime,
            'Period' => $period,
            'Statistics' => $statistics,
            'Unit' => $unit
        ]);

        $message = '';

        if (isset($result['@metadata']['effectiveUri'])) {
            $message .= 'For the effective URI at ' .
                $result['@metadata']['effectiveUri'] . "\n\n";

            if (
                (isset($result['Datapoints'])) and
                (count($result['Datapoints']) > 0)
            ) {
                $message .= "Datapoints found:\n\n";

                foreach ($result['Datapoints'] as $datapoint) {
                    foreach ($datapoint as $key => $value) {
                        $message .= $key . ' = ' . $value . "\n";
                    }

                    $message .= "\n";
                }
            } else {
                $message .= 'No datapoints found.';
            }
        } else {
            $message .= 'No datapoints found.';
        }

        return $message;
    } catch (AwsException $e) {
        return 'Error: ' . $e->getAwsErrorMessage();
    }
}

function getTheMetricStatistics()
{
    // Average number of Amazon EC2 vCPUs every 5 minutes within
    // the past 3 hours.
    $namespace = 'AWS/Usage';
    $metricName = 'ResourceCount';
    $dimensions = [
        [
            'Name' => 'Service',
            'Value' => 'EC2'
        ],
        [
            'Name' => 'Resource',
            'Value' => 'vCPU'
        ],
        [
            'Name' => 'Type',
            'Value' => 'Resource'
        ],
        [
            'Name' => 'Class',
            'Value' => 'Standard/OnDemand'
        ]
    ];
    $startTime = strtotime('-3 hours');
    $endTime = strtotime('now');
    $period = 300; // Seconds. (5 minutes = 300 seconds.)
    $statistics = ['Average'];
    $unit = 'None';

    $cloudWatchClient = new CloudWatchClient([
        'profile' => 'default',
        'region' => 'us-east-1',
        'version' => '2010-08-01'
    ]);

    echo getMetricStatistics(
        $cloudWatchClient,
        $namespace,
        $metricName,
        $dimensions,
        $startTime,
        $endTime,
        $period,
        $statistics,
        $unit
    );

    // Another example: average number of bytes of standard storage in the
    // specified Amazon S3 bucket each day for the past 3 days.

    /*
    $namespace = 'AWS/S3';
    $metricName = 'BucketSizeBytes';
    $dimensions = [
        [
            'Name' => 'StorageType',
            'Value'=> 'StandardStorage'
        ],
        [
            'Name' => 'BucketName',
            'Value' => 'amzn-s3-demo-bucket'
        ]
    ];
    $startTime = strtotime('-3 days');
    $endTime = strtotime('now');
    $period = 86400; // Seconds. (1 day = 86400 seconds.)
    $statistics = array('Average');
    $unit = 'Bytes';

    $cloudWatchClient = new CloudWatchClient([
        'profile' => 'default',
        'region' => 'us-east-1',
        'version' => '2010-08-01'
    ]);

    echo getMetricStatistics($cloudWatchClient, $namespace, $metricName,
    $dimensions, $startTime, $endTime, $period, $statistics, $unit);
    */
}

// Uncomment the following line to run this code in an AWS account.
// getTheMetricStatistics();
```

# 使用 适用于 PHP 的 AWS SDK 版本 3来在 Amazon CloudWatch 中发布自定义指标
<a name="cw-examples-publishing-custom-metrics"></a>

指标是关于您的系统性能的数据。警报会在您规定的时间范围内监控某一项指标。它在多个时间段内根据相对于给定阈值的指标值，执行一项或多项操作。

以下示例演示如何：
+ 使用 [PutMetricData](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-monitoring-2010-08-01.html#putmetricdata) 发布指标数据。
+ 使用 [PutMetricAlarm](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-monitoring-2010-08-01.html#putmetricalarm) 创建警报。

适用于 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) 中所述。

## 发布指标数据
<a name="publish-metric-data"></a>

 **导入**。

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

use Aws\CloudWatch\CloudWatchClient;
use Aws\Exception\AwsException;
```

 **示例代码** 

```
function putMetricData(
    $cloudWatchClient,
    $cloudWatchRegion,
    $namespace,
    $metricData
) {
    try {
        $result = $cloudWatchClient->putMetricData([
            'Namespace' => $namespace,
            'MetricData' => $metricData
        ]);

        if (isset($result['@metadata']['effectiveUri'])) {
            if (
                $result['@metadata']['effectiveUri'] ==
                'https://monitoring.' . $cloudWatchRegion . '.amazonaws.com'
            ) {
                return 'Successfully published datapoint(s).';
            } else {
                return 'Could not publish datapoint(s).';
            }
        } else {
            return 'Error: Could not publish datapoint(s).';
        }
    } catch (AwsException $e) {
        return 'Error: ' . $e->getAwsErrorMessage();
    }
}

function putTheMetricData()
{
    $namespace = 'MyNamespace';
    $metricData = [
        [
            'MetricName' => 'MyMetric',
            'Timestamp' => 1589228818, // 11 May 2020, 20:26:58 UTC.
            'Dimensions' => [
                [
                    'Name' => 'MyDimension1',
                    'Value' => 'MyValue1'

                ],
                [
                    'Name' => 'MyDimension2',
                    'Value' => 'MyValue2'
                ]
            ],
            'Unit' => 'Count',
            'Value' => 1
        ]
    ];

    $cloudWatchRegion = 'us-east-1';
    $cloudWatchClient = new CloudWatchClient([
        'profile' => 'default',
        'region' => $cloudWatchRegion,
        'version' => '2010-08-01'
    ]);

    echo putMetricData(
        $cloudWatchClient,
        $cloudWatchRegion,
        $namespace,
        $metricData
    );
}

// Uncomment the following line to run this code in an AWS account.
// putTheMetricData();
```

## 创建警报
<a name="create-an-alarm"></a>

 **导入**。

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

use Aws\CloudWatch\CloudWatchClient;
use Aws\Exception\AwsException;
```

 **示例代码** 

```
function putMetricAlarm(
    $cloudWatchClient,
    $cloudWatchRegion,
    $alarmName,
    $namespace,
    $metricName,
    $dimensions,
    $statistic,
    $period,
    $comparison,
    $threshold,
    $evaluationPeriods
) {
    try {
        $result = $cloudWatchClient->putMetricAlarm([
            'AlarmName' => $alarmName,
            'Namespace' => $namespace,
            'MetricName' => $metricName,
            'Dimensions' => $dimensions,
            'Statistic' => $statistic,
            'Period' => $period,
            'ComparisonOperator' => $comparison,
            'Threshold' => $threshold,
            'EvaluationPeriods' => $evaluationPeriods
        ]);

        if (isset($result['@metadata']['effectiveUri'])) {
            if (
                $result['@metadata']['effectiveUri'] ==
                'https://monitoring.' . $cloudWatchRegion . '.amazonaws.com'
            ) {
                return 'Successfully created or updated specified alarm.';
            } else {
                return 'Could not create or update specified alarm.';
            }
        } else {
            return 'Could not create or update specified alarm.';
        }
    } catch (AwsException $e) {
        return 'Error: ' . $e->getAwsErrorMessage();
    }
}

function putTheMetricAlarm()
{
    $alarmName = 'my-ec2-resources';
    $namespace = 'AWS/Usage';
    $metricName = 'ResourceCount';
    $dimensions = [
        [
            'Name' => 'Type',
            'Value' => 'Resource'
        ],
        [
            'Name' => 'Resource',
            'Value' => 'vCPU'
        ],
        [
            'Name' => 'Service',
            'Value' => 'EC2'
        ],
        [
            'Name' => 'Class',
            'Value' => 'Standard/OnDemand'
        ]
    ];
    $statistic = 'Average';
    $period = 300;
    $comparison = 'GreaterThanThreshold';
    $threshold = 1;
    $evaluationPeriods = 1;

    $cloudWatchRegion = 'us-east-1';
    $cloudWatchClient = new CloudWatchClient([
        'profile' => 'default',
        'region' => $cloudWatchRegion,
        'version' => '2010-08-01'
    ]);

    echo putMetricAlarm(
        $cloudWatchClient,
        $cloudWatchRegion,
        $alarmName,
        $namespace,
        $metricName,
        $dimensions,
        $statistic,
        $period,
        $comparison,
        $threshold,
        $evaluationPeriods
    );
}

// Uncomment the following line to run this code in an AWS account.
// putTheMetricAlarm();
```

# 使用 适用于 PHP 的 AWS SDK 版本 3 向 Amazon CloudWatch 活动发送事件
<a name="cw-examples-sending-events"></a>

CloudWatch 事件向任意目标提供近乎实时的系统事件流，这些事件描述了 Amazon Web Services (AWS) 资源的变化。通过简单规则，您可以匹配事件并将事件路由到一个或多个目标函数或流。

以下示例演示如何：
+ 使用创建规则[PutRule](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-events-2015-10-07.html#putrule)。
+ 使用向规则添加目标[PutTargets](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-events-2015-10-07.html#puttargets)。
+ 使用向事件发送自定义 CloudWatch 事件[PutEvents](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-events-2015-10-07.html#putevents)。

的所有示例代码都可以在[此 适用于 PHP 的 AWS SDK 处找到 GitHub](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)。

## 创建规则
<a name="create-a-rule"></a>

 **导入** 

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

use Aws\Exception\AwsException;
```

 **示例代码** 

```
$client = new Aws\cloudwatchevents\cloudwatcheventsClient([
    'profile' => 'default',
    'region' => 'us-west-2',
    'version' => '2015-10-07'
]);

try {
    $result = $client->putRule([
        'Name' => 'DEMO_EVENT', // REQUIRED
        'RoleArn' => 'IAM_ROLE_ARN',
        'ScheduleExpression' => 'rate(5 minutes)',
        'State' => 'ENABLED',
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    error_log($e->getMessage());
}
```

## 向规则中添加目标
<a name="add-targets-to-a-rule"></a>

 **导入** 

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

use Aws\Exception\AwsException;
```

 **示例代码** 

```
$client = new Aws\cloudwatchevents\cloudwatcheventsClient([
    'profile' => 'default',
    'region' => 'us-west-2',
    'version' => '2015-10-07'
]);

try {
    $result = $client->putTargets([
        'Rule' => 'DEMO_EVENT', // REQUIRED
        'Targets' => [ // REQUIRED
            [
                'Arn' => 'LAMBDA_FUNCTION_ARN', // REQUIRED
                'Id' => 'myCloudWatchEventsTarget' // REQUIRED
            ],
        ],
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    error_log($e->getMessage());
}
```

## 发送自定义事件
<a name="send-custom-events"></a>

 **导入** 

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

use Aws\Exception\AwsException;
```

 **示例代码** 

```
$client = new Aws\cloudwatchevents\cloudwatcheventsClient([
    'profile' => 'default',
    'region' => 'us-west-2',
    'version' => '2015-10-07'
]);

try {
    $result = $client->putEvents([
        'Entries' => [ // REQUIRED
            [
                'Detail' => '<string>',
                'DetailType' => '<string>',
                'Resources' => ['<string>'],
                'Source' => '<string>',
                'Time' => time()
            ],
        ],
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    error_log($e->getMessage());
}
```

# 使用 适用于 PHP 的 AWS SDK 版本 3 来将警报操作用于 Amazon CloudWatch 警报
<a name="cw-examples-using-alarm-actions"></a>

利用警报操作创建自动停止、终止、重启或恢复 Amazon EC2 实例的警报。当不再需要某个实例运行时，您可使用停止或终止操作。使用重启和恢复操作可以自动重启这些实例。

以下示例演示如何：
+ 使用 [EnableAlarmActions](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-monitoring-2010-08-01.html#enablealarmactions) 为指定的警报启用操作。
+ 使用 [DisableAlarmActions](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-monitoring-2010-08-01.html#disablealarmactions) 为指定的警报禁用操作。

适用于 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) 中所述。

## 启用警报操作
<a name="enable-alarm-actions"></a>

 **导入**。

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

use Aws\CloudWatch\CloudWatchClient;
use Aws\Exception\AwsException;
```

 **示例代码** 

```
function enableAlarmActions($cloudWatchClient, $alarmNames)
{
    try {
        $result = $cloudWatchClient->enableAlarmActions([
            'AlarmNames' => $alarmNames
        ]);

        if (isset($result['@metadata']['effectiveUri'])) {
            return 'At the effective URI of ' .
                $result['@metadata']['effectiveUri'] .
                ', actions for any matching alarms have been enabled.';
        } else {
            return'Actions for some matching alarms ' .
                'might not have been enabled.';
        }
    } catch (AwsException $e) {
        return 'Error: ' . $e->getAwsErrorMessage();
    }
}

function enableTheAlarmActions()
{
    $alarmNames = array('my-alarm');

    $cloudWatchClient = new CloudWatchClient([
        'profile' => 'default',
        'region' => 'us-east-1',
        'version' => '2010-08-01'
    ]);

    echo enableAlarmActions($cloudWatchClient, $alarmNames);
}

// Uncomment the following line to run this code in an AWS account.
// enableTheAlarmActions();
```

## 禁用警报操作
<a name="disable-alarm-actions"></a>

 **导入**。

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

use Aws\CloudWatch\CloudWatchClient;
use Aws\Exception\AwsException;
```

 **示例代码** 

```
function disableAlarmActions($cloudWatchClient, $alarmNames)
{
    try {
        $result = $cloudWatchClient->disableAlarmActions([
            'AlarmNames' => $alarmNames
        ]);

        if (isset($result['@metadata']['effectiveUri'])) {
            return 'At the effective URI of ' .
                $result['@metadata']['effectiveUri'] .
                ', actions for any matching alarms have been disabled.';
        } else {
            return 'Actions for some matching alarms ' .
                'might not have been disabled.';
        }
    } catch (AwsException $e) {
        return 'Error: ' . $e->getAwsErrorMessage();
    }
}

function disableTheAlarmActions()
{
    $alarmNames = array('my-alarm');

    $cloudWatchClient = new CloudWatchClient([
        'profile' => 'default',
        'region' => 'us-east-1',
        'version' => '2010-08-01'
    ]);

    echo disableAlarmActions($cloudWatchClient, $alarmNames);
}

// Uncomment the following line to run this code in an AWS account.
// disableTheAlarmActions();
```

# 使用 适用于 PHP 的 AWS SDK 版本 3 的 Amazon EC2 示例
<a name="ec2-examples"></a>

Amazon Elastic Compute Cloud (Amazon EC2) 是一项 Web 服务，可在云中提供虚拟服务器托管。该服务旨在通过提供大小可调整的计算容量来降低开发人员进行网络级云计算的难度。

适用于 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) 中所述。

**Topics**
+ [凭证](#examplecredentials)
+ [管理 Amazon EC2 实例](ec2-examples-managing-instances.md)
+ [使用弹性 IP 地址](ec2-examples-using-elastic-ip-addresses.md)
+ [使用区域和可用区](ec2-examples-using-regions-and-zones.md)
+ [使用密钥对](ec2-examples-working-with-key-pairs.md)
+ [使用安全组](ec2-examples-using-security-groups.md)

# 使用 适用于 PHP 的 AWS SDK 版本 3 来管理 Amazon EC2 实例
<a name="ec2-examples-managing-instances"></a>

以下示例演示如何：
+ 使用 [DescribeInstances](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-ec2-2016-11-15.html#describeinstances) 描述 Amazon EC2 实例。
+ 使用 [MonitorInstances](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-ec2-2016-11-15.html#monitorinstances) 为正在运行的实例启用详细监控。
+ 使用 [UnmonitorInstances](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-ec2-2016-11-15.html#unmonitorinstances) 为正在运行的实例禁用监控。
+ 使用 [StartInstances](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-ec2-2016-11-15.html#startinstances) 启动之前停止的 Amazon EBS-backed AMI。
+ 使用 [StopInstances](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-ec2-2016-11-15.html#stopinstances) 停止由 Amazon EBS 支持的实例。
+ 使用 [RebootInstances](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-ec2-2016-11-15.html#rebootinstances) 请求重新启动一个或多个实例。

适用于 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) 中所述。

## 描述实例
<a name="describe-instances"></a>

 **导入**。

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

use Aws\Ec2\Ec2Client;
```

 **示例代码** 

```
$ec2Client = new Aws\Ec2\Ec2Client([
    'region' => 'us-west-2',
    'version' => '2016-11-15',
    'profile' => 'default'
]);
$result = $ec2Client->describeInstances();
echo "Instances: \n";
foreach ($result['Reservations'] as $reservation) {
    foreach ($reservation['Instances'] as $instance) {
        echo "InstanceId: {$instance['InstanceId']} - {$instance['State']['Name']} \n";
    }
}
```

## 启用和禁用监控
<a name="enable-and-disable-monitoring"></a>

 **导入**。

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

 **示例代码** 

```
$ec2Client = new Aws\Ec2\Ec2Client([
    'region' => 'us-west-2',
    'version' => '2016-11-15',
    'profile' => 'default'
]);

$instanceIds = ['InstanceID1', 'InstanceID2'];

$monitorInstance = 'ON';

if ($monitorInstance == 'ON') {
    $result = $ec2Client->monitorInstances([
        'InstanceIds' => $instanceIds
    ]);
} else {
    $result = $ec2Client->unmonitorInstances([
        'InstanceIds' => $instanceIds
    ]);
}

var_dump($result);
```

## 启动和停止 实例
<a name="start-and-stop-an-instance"></a>

 **导入**。

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

 **示例代码** 

```
$ec2Client = new Aws\Ec2\Ec2Client([
    'region' => 'us-west-2',
    'version' => '2016-11-15',
    'profile' => 'default'
]);

$action = 'START';

$instanceIds = ['InstanceID1', 'InstanceID2'];

if ($action == 'START') {
    $result = $ec2Client->startInstances([
        'InstanceIds' => $instanceIds,
    ]);
} else {
    $result = $ec2Client->stopInstances([
        'InstanceIds' => $instanceIds,
    ]);
}

var_dump($result);
```

## 重启实例
<a name="reboot-an-instance"></a>

 **导入**。

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

 **示例代码** 

```
$ec2Client = new Aws\Ec2\Ec2Client([
    'region' => 'us-west-2',
    'version' => '2016-11-15',
    'profile' => 'default'
]);

$instanceIds = ['InstanceID1', 'InstanceID2'];

$result = $ec2Client->rebootInstances([
    'InstanceIds' => $instanceIds
]);

var_dump($result);
```

# 在 适用于 PHP 的 AWS SDK 版本 3 的 Amazon EC2 上使用弹性 IP 地址
<a name="ec2-examples-using-elastic-ip-addresses"></a>

弹性 IP 地址是专为动态云计算设计的静态 IP 地址。弹性 IP 地址与您的关联 AWS 账户。它是公有 IP 地址，可从 Internet 访问。如果您的实例没有公有 IP 地址，则可以将弹性 IP 地址与您的实例关联以启用与 Internet 的通信。

以下示例演示如何：
+ 使用描述您的一个或多个实例[DescribeInstances](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-ec2-2016-11-15.html#describeinstances)。
+ 使用获取弹性 IP 地址[AllocateAddress](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-ec2-2016-11-15.html#allocateaddress)。
+ 使用将弹性 IP 地址与实例关联起来[AssociateAddress](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-ec2-2016-11-15.html#associateaddress)。
+ 使用释放弹性 IP 地址[ReleaseAddress](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-ec2-2016-11-15.html#releaseaddress)。

的所有示例代码都可以在[此 适用于 PHP 的 AWS SDK 处找到 GitHub](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)。

## 描述实例
<a name="describe-an-instance"></a>

 **导入** 

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

use Aws\Ec2\Ec2Client;
```

 **示例代码** 

```
$ec2Client = new Aws\Ec2\Ec2Client([
    'region' => 'us-west-2',
    'version' => '2016-11-15',
    'profile' => 'default'
]);
$result = $ec2Client->describeInstances();
echo "Instances: \n";
foreach ($result['Reservations'] as $reservation) {
    foreach ($reservation['Instances'] as $instance) {
        echo "InstanceId: {$instance['InstanceId']} - {$instance['State']['Name']} \n";
    }
}
```

## 分配和关联地址
<a name="allocate-and-associate-an-address"></a>

 **导入** 

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

 **示例代码** 

```
$ec2Client = new Aws\Ec2\Ec2Client([
    'region' => 'us-west-2',
    'version' => '2016-11-15',
    'profile' => 'default'
]);

$instanceId = 'InstanceID';

$allocation = $ec2Client->allocateAddress(array(
    'DryRun' => false,
    'Domain' => 'vpc',
));

$result = $ec2Client->associateAddress(array(
    'DryRun' => false,
    'InstanceId' => $instanceId,
    'AllocationId' => $allocation->get('AllocationId')
));

var_dump($result);
```

## 发布地址
<a name="release-an-address"></a>

 **导入** 

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

 **示例代码** 

```
$ec2Client = new Aws\Ec2\Ec2Client([
    'region' => 'us-west-2',
    'version' => '2016-11-15',
    'profile' => 'default'
]);

$associationID = 'AssociationID';

$allocationID = 'AllocationID';

$result = $ec2Client->disassociateAddress([
    'AssociationId' => $associationID,
]);

$result = $ec2Client->releaseAddress([
    'AllocationId' => $allocationID,
]);

var_dump($result);
```

# 使用 适用于 PHP 的 AWS SDK 版本 3 来使用用于 Amazon EC2 的区域和可用区
<a name="ec2-examples-using-regions-and-zones"></a>

Amazon EC2 托管在全球多个位置。这些位置由 AWS 区域和可用区构成。每个区域都是一个独立的地理区域，其中包含多个相互隔离的位置，这些位置称为可用区。Amazon EC2 提供了将实例和数据放在多个位置的功能。

以下示例演示如何：
+ 使用 [DescribeAvailabilityZones](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-ec2-2016-11-15.html#describeavailabilityzones) 描述可供您使用的可用区。
+ 使用 [DescribeRegions](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-ec2-2016-11-15.html#describeregions) 描述当前可供您使用的 AWS 区域。

适用于 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) 中所述。

## 描述可用区
<a name="describe-availability-zones"></a>

 **导入**。

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

 **示例代码** 

```
$ec2Client = new Aws\Ec2\Ec2Client([
    'region' => 'us-west-2',
    'version' => '2016-11-15',
    'profile' => 'default'
]);

$result = $ec2Client->describeAvailabilityZones();

var_dump($result);
```

## 描述区域
<a name="describe-regions"></a>

 **导入**。

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

 **示例代码** 

```
$ec2Client = new Aws\Ec2\Ec2Client([
    'region' => 'us-west-2',
    'version' => '2016-11-15',
    'profile' => 'default'
]);

$result = $ec2Client->describeRegions();

var_dump($result);
```

# 结合使用 Amazon EC2 密钥对与 适用于 PHP 的 AWS SDK 版本 3
<a name="ec2-examples-working-with-key-pairs"></a>

Amazon EC2 使用公有密钥密码系统来加密和解密登录信息。公有密钥加密法使用公有密钥来加密数据。随后，收件人使用私有密钥解密数据。公有和私有密钥被称为密钥对。

以下示例演示如何：
+ 使用 [CreateKeyPair](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-ec2-2016-11-15.html#createkeypair) 创建 2048 位 RSA 密钥对。
+ 使用 [DeleteKeyPair](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-ec2-2016-11-15.html#deletekeypair) 删除指定密钥对。
+ 使用 [DescribeKeyPairs](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-ec2-2016-11-15.html#describekeypairs) 描述一个或多个密钥对。

适用于 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) 中所述。

## 创建密钥对
<a name="create-a-key-pair"></a>

 **导入**。

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

 **示例代码** 

```
$ec2Client = new Aws\Ec2\Ec2Client([
    'region' => 'us-west-2',
    'version' => '2016-11-15',
    'profile' => 'default'
]);

$keyPairName = 'my-keypair';

$result = $ec2Client->createKeyPair(array(
    'KeyName' => $keyPairName
));

// Save the private key
$saveKeyLocation = getenv('HOME') . "/.ssh/{$keyPairName}.pem";
file_put_contents($saveKeyLocation, $result['keyMaterial']);

// Update the key's permissions so it can be used with SSH
chmod($saveKeyLocation, 0600);
```

## 删除密钥对
<a name="delete-a-key-pair"></a>

 **导入**。

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

 **示例代码** 

```
$ec2Client = new Aws\Ec2\Ec2Client([
    'region' => 'us-west-2',
    'version' => '2016-11-15',
    'profile' => 'default'
]);

$keyPairName = 'my-keypair';

$result = $ec2Client->deleteKeyPair(array(
    'KeyName' => $keyPairName
));

var_dump($result);
```

## 描述密钥对
<a name="describe-key-pairs"></a>

 **导入**。

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

 **示例代码** 

```
$ec2Client = new Aws\Ec2\Ec2Client([
    'region' => 'us-west-2',
    'version' => '2016-11-15',
    'profile' => 'default'
]);

$result = $ec2Client->describeKeyPairs();

var_dump($result);
```

# 在 Amazon EC2 中结合使用安全组与 适用于 PHP 的 AWS SDK 版本 3
<a name="ec2-examples-using-security-groups"></a>

Amazon EC2 安全组起着虚拟防火墙的作用，可控制一个或多个实例的流量。为每个安全组添加规则来规定流入或流出其关联实例的流量。您可以随时修改安全组的规则。新规则将自动应用于与安全组相关联的所有实例。

以下示例演示如何：
+ 使用 [DescribeSecurityGroups](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-ec2-2016-11-15.html#describesecuritygroups) 描述一个或多个安全组。
+ 使用 [AuthorizeSecurityGroupIngress](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-ec2-2016-11-15.html#authorizesecuritygroupingress) 向安全组添加入口规则。
+ 使用 [CreateSecurityGroup](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-ec2-2016-11-15.html#createsecuritygroup) 创建安全组。
+ 使用 [DeleteSecurityGroup](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-ec2-2016-11-15.html#deletesecuritygroup) 删除安全组。

适用于 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) 中所述。

## 描述安全组
<a name="describe-security-groups"></a>

 **导入**。

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

 **示例代码** 

```
$ec2Client = new Aws\Ec2\Ec2Client([
    'region' => 'us-west-2',
    'version' => '2016-11-15',
    'profile' => 'default'
]);

$result = $ec2Client->describeSecurityGroups();

var_dump($result);
```

## 添加入口规则
<a name="add-an-ingress-rule"></a>

 **导入**。

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

 **示例代码** 

```
$ec2Client = new Aws\Ec2\Ec2Client([
    'region' => 'us-west-2',
    'version' => '2016-11-15',
    'profile' => 'default'
]);

$result = $ec2Client->authorizeSecurityGroupIngress(array(
    'GroupName' => 'string',
    'SourceSecurityGroupName' => 'string'
));

var_dump($result);
```

## 创建安全组
<a name="create-a-security-group"></a>

 **导入**。

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

 **示例代码** 

```
$ec2Client = new Aws\Ec2\Ec2Client([
    'region' => 'us-west-2',
    'version' => '2016-11-15',
    'profile' => 'default'
]);

// Create the security group
$securityGroupName = 'my-security-group';
$result = $ec2Client->createSecurityGroup(array(
    'GroupId' => $securityGroupName,

));

// Get the security group ID (optional)
$securityGroupId = $result->get('GroupId');

echo "Security Group ID: " . $securityGroupId . '\n';
```

## 删除安全组
<a name="delete-a-security-group"></a>

 **导入**。

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

 **示例代码** 

```
$ec2Client = new Aws\Ec2\Ec2Client([
    'region' => 'us-west-2',
    'version' => '2016-11-15',
    'profile' => 'default'
]);

$securityGroupId = 'my-security-group-id';

$result = $ec2Client->deleteSecurityGroup([
    'GroupId' => $securityGroupId
]);

var_dump($result);
```

# 使用 适用于 PHP 的 AWS SDK 版本 3 来签署 Amazon OpenSearch Service 搜索请求
<a name="service_es-data-plane"></a>

Amazon OpenSearch Service 是一项托管服务，让用户能够轻松地部署、操作和扩展 Amazon OpenSearch Service（一个流行的开源搜索和分析引擎）。OpenSearch Service 支持直接访问 Amazon OpenSearch Service API。这意味着，开发人员可以使用他们熟悉的工具以及强大的安全选项。许多 Amazon OpenSearch Service 客户端都支持请求签名，但如果您使用的客户端不支持，则可以使用 适用于 PHP 的 AWS SDK 的内置凭证提供程序和签署人对任意 PSR-7 请求签名。

以下示例演示如何：
+ 使用 [SignatureV4](https://docs.aws.amazon.com/aws-sdk-php/v3/api/class-Aws.Signature.SignatureV4.html#_signRequest) 通过 AWS 签名协议签署请求。

适用于 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) 中所述。

## 签署 OpenSearch Service 请求
<a name="signing-an-es-request"></a>

OpenSearch Service 使用[签名版本 4](https://docs.aws.amazon.com/general/latest/gr/signature-version-4.html)。这意味着，您需要根据服务的签名名称（在此示例中为 `es`）和 OpenSearch Service 域的 AWS 区域来签署请求。在 Amazon Web Services 一般参考 中的 [AWS 区域和终端节点页面上](https://docs.aws.amazon.com/general/latest/gr/rande.html)可以找到 OpenSearch Service 支持区域的完整列表。但在此示例中，我们将针对 `us-west-2` 区域中的 OpenSearch Service 域来签署请求。

您需要提供凭证，可以通过 SDK 的默认凭证提供程序链或通过 [适用于 PHP 的 AWS SDK 版本 3 的凭证](guide_credentials.md)中介绍的任何形式的凭证来提供。您还将需要一个 [PSR-7 请求](https://docs.aws.amazon.com/aws-sdk-php/v3/api/class-Psr.Http.Message.RequestInterface.html)（在下面的代码中假定名为 `$psr7Request`）。

```
// Pull credentials from the default provider chain
$provider = Aws\Credentials\CredentialProvider::defaultProvider();
$credentials = call_user_func($provider)->wait();

// Create a signer with the service's signing name and Region
$signer = new Aws\Signature\SignatureV4('es', 'us-west-2');

// Sign your request
$signedRequest = $signer->signRequest($psr7Request, $credentials);
```

# 使用 适用于 PHP 的 AWS SDK 版本 3 的 AWS Identity and Access Management 示例
<a name="iam-examples"></a>

AWS Identity and Access Management (IAM) 是一项 Web 服务，支持 Amazon Web Services 客户在 AWS 中管理用户和用户权限。该服务面向在云中有多个使用 AWS 产品的用户或系统的组织。借助 IAM，您可以集中管理用户、安全凭证（如访问密钥），以及控制用户可访问何种 AWS 资源的权限。

适用于 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) 中所述。

**Topics**
+ [凭证](#examplecredentials)
+ [管理 IAM 访问密钥](iam-examples-managing-access-keys.md)
+ [管理 IAM 用户](iam-examples-managing-users.md)
+ [使用 IAM 账户别名](iam-examples-using-account-aliases.md)
+ [使用 IAM 策略](iam-examples-working-with-policies.md)
+ [使用 IAM 服务器证书](iam-examples-working-with-certs.md)

# 使用 适用于 PHP 的 AWS SDK 版本 3 来管理 IAM 访问密钥
<a name="iam-examples-managing-access-keys"></a>

用户需要自己的访问密钥以编程方式调用 AWS。要满足这一需要，您可以创建、修改、查看或轮换 IAM 用户的访问密钥 (访问密钥 ID 和秘密访问密钥)。默认情况下，当您创建访问密钥时，其状态为“活动”。这表示用户可以将访问密钥用于 API 调用。

以下示例演示如何：
+ 使用 [CreateAccessKey](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-iam-2010-05-08.html#createaccesskey) 创建秘密访问密钥和相应的访问密钥 ID。
+ 使用 [ListAccessKeys](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-iam-2010-05-08.html#listaccesskeys) 返回有关与 IAM 用户关联的访问密钥 ID 的信息。
+ 使用 [GetAccessKeyLastUsed](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-iam-2010-05-08.html#getaccesskeylastused) 检索有关上次使用访问密钥的时间的信息。
+ 使用 [UpdateAccessKey](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-iam-2010-05-08.html#updateaccesskey) 将访问密钥的状态从“Active”更改为“Inactive”或相反。
+ 使用 [DeleteAccessKey](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-iam-2010-05-08.html#deleteaccesskey) 删除与 IAM 用户关联的访问密钥对。

适用于 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) 中所述。

## 创建访问密钥
<a name="create-an-access-key"></a>

 **导入**。

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

use Aws\Exception\AwsException;
use Aws\Iam\IamClient;
```

 **示例代码** 

```
$client = new IamClient([
    'profile' => 'default',
    'region' => 'us-west-2',
    'version' => '2010-05-08'
]);

try {
    $result = $client->createAccessKey([
        'UserName' => 'IAM_USER_NAME',
    ]);
    $keyID = $result['AccessKey']['AccessKeyId'];
    $createDate = $result['AccessKey']['CreateDate'];
    $userName = $result['AccessKey']['UserName'];
    $status = $result['AccessKey']['Status'];
    // $secretKey = $result['AccessKey']['SecretAccessKey']
    echo "<p>AccessKey " . $keyID . " created on " . $createDate . "</p>";
    echo "<p>Username: " . $userName . "</p>";
    echo "<p>Status: " . $status . "</p>";
} catch (AwsException $e) {
    // output error message if fails
    error_log($e->getMessage());
}
```

## 列出访问密钥
<a name="list-access-keys"></a>

 **导入**。

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

use Aws\Exception\AwsException;
use Aws\Iam\IamClient;
```

 **示例代码** 

```
$client = new IamClient([
    'profile' => 'default',
    'region' => 'us-west-2',
    'version' => '2010-05-08'
]);

try {
    $result = $client->listAccessKeys();
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    error_log($e->getMessage());
}
```

## 获取有关上次使用访问密钥的信息
<a name="get-information-about-an-access-key-s-last-use"></a>

 **导入**。

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

use Aws\Exception\AwsException;
use Aws\Iam\IamClient;
```

 **示例代码** 

```
$client = new IamClient([
    'profile' => 'default',
    'region' => 'us-west-2',
    'version' => '2010-05-08'
]);

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

## 更新访问密钥
<a name="update-an-access-key"></a>

 **导入**。

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

use Aws\Exception\AwsException;
use Aws\Iam\IamClient;
```

 **示例代码** 

```
$client = new IamClient([
    'profile' => 'default',
    'region' => 'us-west-2',
    'version' => '2010-05-08'
]);

try {
    $result = $client->updateAccessKey([
        'AccessKeyId' => 'ACCESS_KEY_ID', // REQUIRED
        'Status' => 'Inactive', // REQUIRED
        'UserName' => 'IAM_USER_NAME',
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    error_log($e->getMessage());
}
```

## 删除访问密钥
<a name="delete-an-access-key"></a>

 **导入**。

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

use Aws\Exception\AwsException;
use Aws\Iam\IamClient;
```

 **示例代码** 

```
$client = new IamClient([
    'profile' => 'default',
    'region' => 'us-west-2',
    'version' => '2010-05-08'
]);

try {
    $result = $client->deleteAccessKey([
        'AccessKeyId' => 'ACCESS_KEY_ID', // REQUIRED
        'UserName' => 'IAM_USER_NAME',
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    error_log($e->getMessage());
}
```

# 使用 适用于 PHP 的 AWS SDK 版本 3 来管理 IAM 用户
<a name="iam-examples-managing-users"></a>

IAM 用户是在 AWS 中创建的一个实体，代表使用其与 AWS 进行交互的人员或服务。AWS 中的用户包括名称和凭证。

以下示例演示如何：
+ 使用 [CreateUser](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-iam-2010-05-08.html#createuser) 创建新 IAM 用户。
+ 使用 [ListUsers](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-iam-2010-05-08.html#listusers) 列出 IAM 用户。
+ 使用 [UpdateUser](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-iam-2010-05-08.html#updateuser) 更新 IAM 用户。
+ 使用 [GetUser](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-iam-2010-05-08.html#getuser) 检索有关 IAM 用户的信息。
+ 使用 [DeleteUser](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-iam-2010-05-08.html#deleteuser) 删除 IAM 用户。

适用于 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) 中所述。

## 创建 IAM 用户
<a name="create-an-iam-user"></a>

 **导入**。

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

use Aws\Exception\AwsException;
use Aws\Iam\IamClient;
```

 **示例代码** 

```
$client = new IamClient([
    'profile' => 'default',
    'region' => 'us-west-2',
    'version' => '2010-05-08'
]);

try {
    $result = $client->createUser(array(
        // UserName is required
        'UserName' => 'string',
    ));
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    error_log($e->getMessage());
}
```

## 列出 IAM 用户
<a name="list-iam-users"></a>

 **导入**。

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

use Aws\Exception\AwsException;
use Aws\Iam\IamClient;
```

 **示例代码** 

```
$client = new IamClient([
    'profile' => 'default',
    'region' => 'us-west-2',
    'version' => '2010-05-08'
]);

try {
    $result = $client->listUsers();
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    error_log($e->getMessage());
}
```

## 更新 IAM 用户
<a name="update-an-iam-user"></a>

 **导入**。

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

use Aws\Exception\AwsException;
use Aws\Iam\IamClient;
```

 **示例代码** 

```
$client = new IamClient([
    'profile' => 'default',
    'region' => 'us-west-2',
    'version' => '2010-05-08'
]);

try {
    $result = $client->updateUser([
        // UserName is required
        'UserName' => 'string1',
        'NewUserName' => 'string'
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    error_log($e->getMessage());
}
```

## 获取有关 IAM 用户的信息
<a name="get-information-about-an-iam-user"></a>

 **导入**。

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

use Aws\Exception\AwsException;
use Aws\Iam\IamClient;
```

 **示例代码** 

```
$client = new IamClient([
    'profile' => 'default',
    'region' => 'us-west-2',
    'version' => '2010-05-08'
]);

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

## 删除 IAM 用户
<a name="delete-an-iam-user"></a>

 **导入**。

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

use Aws\Exception\AwsException;
use Aws\Iam\IamClient;
```

 **示例代码** 

```
$client = new IamClient([
    'profile' => 'default',
    'region' => 'us-west-2',
    'version' => '2010-05-08'
]);

try {
    $result = $client->deleteUser([
        // UserName is required
        'UserName' => 'string'
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    error_log($e->getMessage());
}
```

# 结合使用 IAM 账户别名与 适用于 PHP 的 AWS SDK 版本 3
<a name="iam-examples-using-account-aliases"></a>

如果您希望登录页面的 URL 包含贵公司名称（或其他友好标识符）而不是 AWS 账户 ID，则可以为 AWS 账户 ID 创建别名。如果创建 AWS 账户 别名，您的登录页面 URL 将更改以包含该别名。

以下示例演示如何：
+ 使用 [CreateAccountAlias](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-iam-2010-05-08.html#createaccountalias) 创建别名。
+ 使用 [ListAccountAliases](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-iam-2010-05-08.html#listaccountaliases) 列出与 AWS 账户 关联的别名。
+ 使用 [DeleteAccountAlias](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-iam-2010-05-08.html#deleteaccountalias) 删除别名。

适用于 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) 中所述。

## 创建别名
<a name="create-an-alias"></a>

 **导入**。

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

use Aws\Exception\AwsException;
use Aws\Iam\IamClient;
```

 **示例代码** 

```
$client = new IamClient([
    'profile' => 'default',
    'region' => 'us-west-2',
    'version' => '2010-05-08'
]);

try {
    $result = $client->createAccountAlias(array(
        // AccountAlias is required
        'AccountAlias' => 'string',
    ));
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    error_log($e->getMessage());
}
```

## 列出账户别名
<a name="list-account-aliases"></a>

 **导入**。

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

use Aws\Exception\AwsException;
use Aws\Iam\IamClient;
```

 **示例代码** 

```
$client = new IamClient([
    'profile' => 'default',
    'region' => 'us-west-2',
    'version' => '2010-05-08'
]);

try {
    $result = $client->listAccountAliases();
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    error_log($e->getMessage());
}
```

## 删除别名
<a name="delete-an-alias"></a>

 **导入**。

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

use Aws\Exception\AwsException;
use Aws\Iam\IamClient;
```

 **示例代码** 

```
$client = new IamClient([
    'profile' => 'default',
    'region' => 'us-west-2',
    'version' => '2010-05-08'
]);

try {
    $result = $client->deleteAccountAlias([
        // AccountAlias is required
        'AccountAlias' => 'string',
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    error_log($e->getMessage());
}
```

# 结合使用 IAM 策略与 适用于 PHP 的 AWS SDK 版本 3
<a name="iam-examples-working-with-policies"></a>

您通过创建策略向用户授予权限。策略是一个文档，其中列出了用户可以执行的操作以及这些操作会影响的资源。默认情况下会拒绝未显式允许的任何操作或资源。可将策略附加到用户、用户组、用户代入的角色以及资源。

以下示例演示如何：
+ 使用 [CreatePolicy](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-iam-2010-05-08.html#createpolicy) 创建托管策略。
+ 使用 [AttachRolePolicy](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-iam-2010-05-08.html#attachrolepolicy) 将策略附加到角色。
+ 使用 [AttachUserPolicy](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-iam-2010-05-08.html#attachuserpolicy) 将策略附加到用户。
+ 使用 [AttachGroupPolicy](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-iam-2010-05-08.html#attachgrouppolicy) 将策略附加到组。
+ 使用 [DetachRolePolicy](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-iam-2010-05-08.html#detachrolepolicy) 删除角色策略。
+ 使用 [DetachUserPolicy](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-iam-2010-05-08.html#detachuserpolicy) 删除用户策略。
+ 使用 [DetachGroupPolicy](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-iam-2010-05-08.html#detachgrouppolicy) 删除组策略。
+ 使用 [DeletePolicy](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-iam-2010-05-08.html#deletepolicy) 删除托管策略。
+ 使用 [DeleteRolePolicy](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-iam-2010-05-08.html#deleterolepolicy) 删除角色策略。
+ 使用 [DeleteUserPolicy](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-iam-2010-05-08.html#deleteuserpolicy) 删除用户策略。
+ 使用 [DeleteGroupPolicy](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-iam-2010-05-08.html#deletegrouppolicy) 删除组策略。

适用于 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) 中所述。

## 创建策略
<a name="create-a-policy"></a>

 **导入**。

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

use Aws\Exception\AwsException;
use Aws\Iam\IamClient;
```

 **示例代码** 

```
$client = new IamClient([
    'profile' => 'default',
    'region' => 'us-west-2',
    'version' => '2010-05-08'
]);

$myManagedPolicy = '{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": "logs:CreateLogGroup",
            "Resource": "RESOURCE_ARN"
        },
        {
            "Effect": "Allow",
            "Action": [
            "dynamodb:DeleteItem",
            "dynamodb:GetItem",
            "dynamodb:PutItem",
            "dynamodb:Scan",
            "dynamodb:UpdateItem"
        ],
            "Resource": "RESOURCE_ARN"
        }
    ]
}';

try {
    $result = $client->createPolicy(array(
        // PolicyName is required
        'PolicyName' => 'myDynamoDBPolicy',
        // PolicyDocument is required
        'PolicyDocument' => $myManagedPolicy
    ));
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    error_log($e->getMessage());
}
```

## 将策略附加到角色
<a name="attach-a-policy-to-a-role"></a>

 **导入**。

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

use Aws\Exception\AwsException;
use Aws\Iam\IamClient;
```

 **示例代码** 

```
$client = new IamClient([
    'profile' => 'default',
    'region' => 'us-west-2',
    'version' => '2010-05-08'
]);

$roleName = 'ROLE_NAME';

$policyName = 'AmazonDynamoDBFullAccess';

$policyArn = 'arn:aws:iam::aws:policy/AmazonDynamoDBFullAccess';

try {
    $attachedRolePolicies = $client->getIterator('ListAttachedRolePolicies', ([
        'RoleName' => $roleName,
    ]));
    if (count($attachedRolePolicies) > 0) {
        foreach ($attachedRolePolicies as $attachedRolePolicy) {
            if ($attachedRolePolicy['PolicyName'] == $policyName) {
                echo $policyName . " is already attached to this role. \n";
                exit();
            }
        }
    }
    $result = $client->attachRolePolicy(array(
        // RoleName is required
        'RoleName' => $roleName,
        // PolicyArn is required
        'PolicyArn' => $policyArn
    ));
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    error_log($e->getMessage());
}
```

## 将策略附加到用户
<a name="attach-a-policy-to-a-user"></a>

 **导入**。

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

use Aws\Exception\AwsException;
use Aws\Iam\IamClient;
```

 **示例代码** 

```
$client = new IamClient([
    'profile' => 'default',
    'region' => 'us-west-2',
    'version' => '2010-05-08'
]);

$userName = 'USER_NAME';

$policyName = 'AmazonDynamoDBFullAccess';

$policyArn = 'arn:aws:iam::aws:policy/AmazonDynamoDBFullAccess';

try {
    $attachedUserPolicies = $client->getIterator('ListAttachedUserPolicies', ([
        'UserName' => $userName,
    ]));
    if (count($attachedUserPolicies) > 0) {
        foreach ($attachedUserPolicies as $attachedUserPolicy) {
            if ($attachedUserPolicy['PolicyName'] == $policyName) {
                echo $policyName . " is already attached to this role. \n";
                exit();
            }
        }
    }
    $result = $client->attachUserPolicy(array(
        // UserName is required
        'UserName' => $userName,
        // PolicyArn is required
        'PolicyArn' => $policyArn,
    ));
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    error_log($e->getMessage());
}
```

## 将策略附加到组
<a name="attach-a-policy-to-a-group"></a>

 **导入**。

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

use Aws\Exception\AwsException;
use Aws\Iam\IamClient;
```

 **示例代码** 

```
$client = new IamClient([
    'profile' => 'default',
    'region' => 'us-west-2',
    'version' => '2010-05-08'
]);

try {
    $result = $client->attachGroupPolicy(array(
        // GroupName is required
        'GroupName' => 'string',
        // PolicyArn is required
        'PolicyArn' => 'string',
    ));
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    error_log($e->getMessage());
}
```

## 分离用户策略
<a name="detach-a-user-policy"></a>

 **导入**。

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

use Aws\Exception\AwsException;
use Aws\Iam\IamClient;
```

 **示例代码** 

```
$client = new IamClient([
    'profile' => 'default',
    'region' => 'us-west-2',
    'version' => '2010-05-08'
]);

try {
    $result = $client->detachUserPolicy([
        // UserName is required
        'UserName' => 'string',
        // PolicyArn is required
        'PolicyArn' => 'string',
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    error_log($e->getMessage());
}
```

## 分离组策略
<a name="detach-a-group-policy"></a>

 **导入**。

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

use Aws\Exception\AwsException;
use Aws\Iam\IamClient;
```

 **示例代码** 

```
$client = new IamClient([
    'profile' => 'default',
    'region' => 'us-west-2',
    'version' => '2010-05-08'
]);

try {
    $result = $client->detachGroupPolicy([
        // GroupName is required
        'GroupName' => 'string',
        // PolicyArn is required
        'PolicyArn' => 'string',
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    error_log($e->getMessage());
}
```

## 删除策略
<a name="delete-a-policy"></a>

 **导入**。

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

use Aws\Exception\AwsException;
use Aws\Iam\IamClient;
```

 **示例代码** 

```
$client = new IamClient([
    'profile' => 'default',
    'region' => 'us-west-2',
    'version' => '2010-05-08'
]);

try {
    $result = $client->deletePolicy(array(
        // PolicyArn is required
        'PolicyArn' => 'string'
    ));
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    error_log($e->getMessage());
}
```

## 删除角色策略
<a name="delete-a-role-policy"></a>

 **导入**。

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

use Aws\Exception\AwsException;
use Aws\Iam\IamClient;
```

 **示例代码** 

```
$client = new IamClient([
    'profile' => 'default',
    'region' => 'us-west-2',
    'version' => '2010-05-08'
]);

try {
    $result = $client->deleteRolePolicy([
        // RoleName is required
        'RoleName' => 'string',
        // PolicyName is required
        'PolicyName' => 'string'
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    error_log($e->getMessage());
}
```

## 删除用户策略
<a name="delete-a-user-policy"></a>

 **导入**。

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

use Aws\Exception\AwsException;
use Aws\Iam\IamClient;
```

 **示例代码** 

```
$client = new IamClient([
    'profile' => 'default',
    'region' => 'us-west-2',
    'version' => '2010-05-08'
]);

try {
    $result = $client->deleteUserPolicy([
        // UserName is required
        'UserName' => 'string',
        // PolicyName is required
        'PolicyName' => 'string',
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    error_log($e->getMessage());
}
```

## 删除组策略
<a name="delete-a-group-policy"></a>

 **导入**。

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

use Aws\Exception\AwsException;
use Aws\Iam\IamClient;
```

 **示例代码** 

```
$client = new IamClient([
    'profile' => 'default',
    'region' => 'us-west-2',
    'version' => '2010-05-08'
]);

try {
    $result = $client->deleteGroupPolicy(array(
        // GroupName is required
        'GroupName' => 'string',
        // PolicyName is required
        'PolicyName' => 'string',
    ));
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    error_log($e->getMessage());
}
```

# 结合使用 IAM 服务器证书与 适用于 PHP 的 AWS SDK 版本 3
<a name="iam-examples-working-with-certs"></a>

要在 AWS 上启用网站或应用程序的 HTTPS 连接，需要 SSL/TLS 服务器证书。要在 AWS 上将从外部提供程序获得的证书与网站或应用程序结合使用，必须将证书上传到 IAM 或者导入 AWS Certificate Manager 。

以下示例演示如何：
+ 使用 [ListServerCertificates](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-iam-2010-05-08.html#listservercertificates) 列出 IAM 中存储的证书。
+ 使用 [GetServerCertificate](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-iam-2010-05-08.html#getservercertificate) 检索有关证书的信息。
+ 使用 [UpdateServerCertificate](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-iam-2010-05-08.html#updateservercertificate) 更新证书。
+ 使用 [DeleteServerCertificate](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-iam-2010-05-08.html#deleteservercertificate) 删除证书。

适用于 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) 中所述。

## 列出服务器证书
<a name="list-server-certificates"></a>

 **导入**。

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

use Aws\Exception\AwsException;
use Aws\Iam\IamClient;
```

 **示例代码** 

```
$client = new IamClient([
    'profile' => 'default',
    'region' => 'us-west-2',
    'version' => '2010-05-08'
]);

try {
    $result = $client->listServerCertificates();
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    error_log($e->getMessage());
}
```

## 检索服务器证书
<a name="retrieve-a-server-certificate"></a>

 **导入**。

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

use Aws\Exception\AwsException;
use Aws\Iam\IamClient;
```

 **示例代码** 

```
$client = new IamClient([
    'profile' => 'default',
    'region' => 'us-west-2',
    'version' => '2010-05-08'
]);

try {
    $result = $client->getServerCertificate([
        // ServerCertificateName is required
        'ServerCertificateName' => 'string',
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    error_log($e->getMessage());
}
```

## 更新服务器证书
<a name="update-a-server-certificate"></a>

 **导入**。

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

use Aws\Exception\AwsException;
use Aws\Iam\IamClient;
```

 **示例代码** 

```
$client = new IamClient([
    'profile' => 'default',
    'region' => 'us-west-2',
    'version' => '2010-05-08'
]);

try {
    $result = $client->updateServerCertificate([
        // ServerCertificateName is required
        'ServerCertificateName' => 'string',
        'NewServerCertificateName' => 'string',
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    error_log($e->getMessage());
}
```

## 删除服务器证书
<a name="delete-a-server-certificate"></a>

 **导入**。

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

use Aws\Exception\AwsException;
use Aws\Iam\IamClient;
```

 **示例代码** 

```
$client = new IamClient([
    'profile' => 'default',
    'region' => 'us-west-2',
    'version' => '2010-05-08'
]);

try {
    $result = $client->deleteServerCertificate([
        // ServerCertificateName is required
        'ServerCertificateName' => 'string',
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    error_log($e->getMessage());
}
```

# 使用 适用于 PHP 的 AWS SDK 版本 3 的 AWS Key Management Service 示例
<a name="kms-examples"></a>

AWS Key Management Service (AWS KMS) 是一项托管服务，可让您轻松创建和控制加密您的数据所用的加密密钥。有关 AWS KMS 的更多信息，请参阅 [Amazon KMS 文档](https://aws.amazon.com/documentation/kms/)。无论是编写安全 PHP 应用程序还是向其他 AWS 服务发送数据，AWS KMS 都可以帮助您控制哪些人可以使用密钥并访问您的加密数据。

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

**Topics**
+ [使用密钥](kms-example-keys.md)
+ [加密和解密数据密钥](kms-example-encrypt.md)
+ [使用密钥策略](kms-example-key-policy.md)
+ [处理授权](kms-example-grants.md)
+ [使用别名](kms-example-alias.md)

# 使用 AWS KMS API 和 适用于 PHP 的 AWS SDK 版本 3 处理密钥
<a name="kms-example-keys"></a>

 AWS Key Management Service (AWS KMS) 中的主要资源是[AWS KMS keys](https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#kms_keys)。您可以使用 KMS 密钥来加密数据。

以下示例演示如何：
+ 使用创建客户 KMS 密钥[CreateKey](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-kms-2014-11-01.html#createkey)。
+ 使用生成数据密钥[GenerateDataKey](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-kms-2014-11-01.html#generatedatakey)。
+ 使用查看 KMS 密钥[DescribeKey](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-kms-2014-11-01.html#describekey)。
+ 使用[ListKeys](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-kms-2014-11-01.html#listkeys)获取 KMS 密钥的密钥 IDs 和密钥 ARNS。
+ 使用启用 KMS 密钥[EnableKey](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-kms-2014-11-01.html#enablekey)。
+ 使用禁用 KMS 密钥[DisableKey](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-kms-2014-11-01.html#disablekey)。

的所有示例代码都可以在[此 适用于 PHP 的 AWS SDK 处找到 GitHub](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)。

有关使用 AWS Key Management Service (AWS KMS) 的更多信息，请参阅《[AWS KMS 开发者指南》](https://docs.aws.amazon.com/kms/latest/developerguide/)。

## 创建 KMS 密钥
<a name="create-a-cmk"></a>

要创建 [KMS 密钥](https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#kms_keys)，请使用[CreateKey](https://docs.aws.amazon.com/kms/latest/APIReference/API_CreateKey.html)操作。

 **导入** 

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

use Aws\Exception\AwsException;
```

 **示例代码** 

```
$KmsClient = new Aws\Kms\KmsClient([
    'profile' => 'default',
    'version' => '2014-11-01',
    'region' => 'us-east-2'
]);

//Creates a customer master key (CMK) in the caller's AWS account.
$desc = "Key for protecting critical data";

try {
    $result = $KmsClient->createKey([
        'Description' => $desc,
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    echo $e->getMessage();
    echo "\n";
}
```

## 生成数据密钥
<a name="generate-a-data-key"></a>

要生成数据加密密钥，请使用[GenerateDataKey](https://docs.aws.amazon.com/kms/latest/APIReference/API_GenerateDataKey.html)操作。该操作返回其创建的数据密钥的明文和加密副本。指定 AWS KMS key 生成数据密钥的。

 **导入** 

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

use Aws\Exception\AwsException;
```

 **示例代码** 

```
$KmsClient = new Aws\Kms\KmsClient([
    'profile' => 'default',
    'version' => '2014-11-01',
    'region' => 'us-east-2'
]);

$keyId = 'arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab';
$keySpec = 'AES_256';

try {
    $result = $KmsClient->generateDataKey([
        'KeyId' => $keyId,
        'KeySpec' => $keySpec,
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    echo $e->getMessage();
    echo "\n";
}
```

## 查看 KMS 密钥
<a name="view-a-cmk"></a>

要获取有关 KMS 密钥的详细信息，包括 KMS 密钥的 Amazon 资源名称 (ARN) 和[密钥状态](https://docs.aws.amazon.com/kms/latest/developerguide/key-state.html)，请使用操作。[DescribeKey](https://docs.aws.amazon.com/kms/latest/APIReference/API_DescribeKey.html)

 `DescribeKey` 不会获取别名。要获取别名，请使用[ListAliases](https://docs.aws.amazon.com/kms/latest/APIReference/API_ListKeys.html)操作。

 **导入** 

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

use Aws\Exception\AwsException;
```

 **示例代码** 

```
$KmsClient = new Aws\Kms\KmsClient([
    'profile' => 'default',
    'version' => '2014-11-01',
    'region' => 'us-east-2'
]);

$keyId = 'arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab';

try {
    $result = $KmsClient->describeKey([
        'KeyId' => $keyId,
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    echo $e->getMessage();
    echo "\n";
}
```

## 获取 KMS 密钥 ARNs 的密钥 ID 和密钥
<a name="get-the-key-id-and-key-arns-of-a-cmk"></a>

要获取 KMS 密钥的 ID 和 ARN，请使用操作。[ListAliases](https://docs.aws.amazon.com/kms/latest/APIReference/API_ListKeys.html)

 **导入** 

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

use Aws\Exception\AwsException;
```

 **示例代码** 

```
$KmsClient = new Aws\Kms\KmsClient([
    'profile' => 'default',
    'version' => '2014-11-01',
    'region' => 'us-east-2'
]);

$limit = 10;

try {
    $result = $KmsClient->listKeys([
        'Limit' => $limit,
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    echo $e->getMessage();
    echo "\n";
}
```

## 启用 KMS 密钥
<a name="enable-a-cmk"></a>

要启用已禁用的 KMS 密钥，请使用[EnableKey](https://docs.aws.amazon.com/kms/latest/APIReference/API_EnableKey.html)操作。

 **导入** 

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

use Aws\Exception\AwsException;
```

 **示例代码** 

```
$KmsClient = new Aws\Kms\KmsClient([
    'profile' => 'default',
    'version' => '2014-11-01',
    'region' => 'us-east-2'
]);

$keyId = 'arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab';

try {
    $result = $KmsClient->enableKey([
        'KeyId' => $keyId,
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    echo $e->getMessage();
    echo "\n";
}
```

## 禁用 KMS 密钥
<a name="disable-a-cmk"></a>

要禁用 KMS 密钥，请使用[DisableKey](https://docs.aws.amazon.com/kms/latest/APIReference/API_DisableKey.html)操作。禁用 KMS 密钥可防止其被使用。

 **导入** 

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

use Aws\Exception\AwsException;
```

 **示例代码** 

```
$KmsClient = new Aws\Kms\KmsClient([
    'profile' => 'default',
    'version' => '2014-11-01',
    'region' => 'us-east-2'
]);

$keyId = 'arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab';

try {
    $result = $KmsClient->disableKey([
        'KeyId' => $keyId,
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    echo $e->getMessage();
    echo "\n";
}
```

# 使用版本 3 加密和解密 AWS KMS 数据密钥 适用于 PHP 的 AWS SDK
<a name="kms-example-encrypt"></a>

数据密钥 是可用于加密数据的加密密钥，包括大量数据和其他数据加密密钥。

您可以使用 AWS Key Management Service's (AWS KMS) [AWS KMS key](https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#kms_keys)生成、加密和解密数据密钥。

以下示例演示如何：
+ 使用 [Encrypt](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-kms-2014-11-01.html#encrypt) 加密数据密钥。
+ 使用 [Decrypt](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-kms-2014-11-01.html#decrypt) 解密数据密钥。
+ 使用[ReEncrypt](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-kms-2014-11-01.html#reencrypt)新的 KMS 密钥重新加密数据密钥。

的所有示例代码都可以在[此 适用于 PHP 的 AWS SDK 处找到 GitHub](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)。

有关使用 AWS Key Management Service (AWS KMS) 的更多信息，请参阅《[AWS KMS 开发者指南》](https://docs.aws.amazon.com/kms/latest/developerguide/)。

## Encrypt
<a name="encrypt"></a>

[Encrypt](https://docs.aws.amazon.com/kms/latest/APIReference/API_Encrypt.html) 操作专用于加密数据密钥，但并不常用。[GenerateDataKey](https://docs.aws.amazon.com/kms/latest/APIReference/API_GenerateDataKey.html)和[GenerateDataKeyWithoutPlaintext](https://docs.aws.amazon.com/kms/latest/APIReference/API_GenerateDataKeyWithoutPlaintext.html)操作返回加密的数据密钥。将加密的数据移到新的 AWS 区域并希望在新区域中使用 KMS 密钥来加密数据密钥时，可以使用 `Encypt` 方法。

 **导入** 

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

use Aws\Exception\AwsException;
```

 **示例代码** 

```
$KmsClient = new Aws\Kms\KmsClient([
    'profile' => 'default',
    'version' => '2014-11-01',
    'region' => 'us-east-2'
]);

$keyId = 'arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab';
$message = pack('c*', 1, 2, 3, 4, 5, 6, 7, 8, 9, 0);

try {
    $result = $KmsClient->encrypt([
        'KeyId' => $keyId,
        'Plaintext' => $message,
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    echo $e->getMessage();
    echo "\n";
}
```

## Decrypt
<a name="decrypt"></a>

要解密数据密钥，请使用 [Decrypt](https://docs.aws.amazon.com/kms/latest/APIReference/API_Decrypt.html) 操作。

您指定的必须`ciphertextBlob`是[GenerateDataKey](https://docs.aws.amazon.com/kms/latest/APIReference/API_GenerateDataKey.html)、[GenerateDataKeyWithoutPlaintext](https://docs.aws.amazon.com/kms/latest/APIReference/API_GenerateDataKeyWithoutPlaintext.html)或 E [ncrypt](https://docs.aws.amazon.com/kms/latest/APIReference/API_Encrypt.html) 响应中`CiphertextBlob`字段的值。

 **导入** 

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

use Aws\Exception\AwsException;
```

 **示例代码** 

```
$KmsClient = new Aws\Kms\KmsClient([
    'profile' => 'default',
    'version' => '2014-11-01',
    'region' => 'us-east-2'
]);

$ciphertext = 'Place your cipher text blob here';

try {
    $result = $KmsClient->decrypt([
        'CiphertextBlob' => $ciphertext,
    ]);
    $plaintext = $result['Plaintext'];
    var_dump($plaintext);
} catch (AwsException $e) {
    // Output error message if fails
    echo $e->getMessage();
    echo "\n";
}
```

## 重新加密
<a name="reencrypt"></a>

要解密加密的数据密钥，然后立即使用其他 KMS 密钥重新加密数据密钥，请使用操作。[ReEncrypt](https://docs.aws.amazon.com/kms/latest/APIReference/API_ReEncrypt.html)这些操作完全在服务器端执行 AWS KMS，因此它们永远不会将你的纯文本暴露在外面。 AWS KMS

您指定的必须`ciphertextBlob`是[GenerateDataKey](https://docs.aws.amazon.com/kms/latest/APIReference/API_GenerateDataKey.html)、[GenerateDataKeyWithoutPlaintext](https://docs.aws.amazon.com/kms/latest/APIReference/API_GenerateDataKeyWithoutPlaintext.html)或 E [ncrypt](https://docs.aws.amazon.com/kms/latest/APIReference/API_Encrypt.html) 响应中`CiphertextBlob`字段的值。

 **导入** 

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

use Aws\Exception\AwsException;
```

 **示例代码** 

```
$KmsClient = new Aws\Kms\KmsClient([
    'profile' => 'default',
    'version' => '2014-11-01',
    'region' => 'us-east-2'
]);

$keyId = 'arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab';
$ciphertextBlob = 'Place your cipher text blob here';

try {
    $result = $KmsClient->reEncrypt([
        'CiphertextBlob' => $ciphertextBlob,
        'DestinationKeyId' => $keyId,
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    echo $e->getMessage();
    echo "\n";
}
```

# 使用 适用于 PHP 的 AWS SDK 版本 3 使用 AWS KMS 密钥策略
<a name="kms-example-key-policy"></a>

在创建 [AWS KMS key](https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#kms_keys) 时，您可以确定能够使用和管理该 KMS 密钥的人员。这些权限包含在名为密钥策略的文档中。您可以随时使用密钥策略添加、移除或修改客户托管 KMS 密钥的权限，但不能编辑托 AWS 管 KMS 密钥的密钥策略。有关更多信息，请参阅 [AWS KMS的身份验证和访问控制](https://docs.aws.amazon.com/kms/latest/developerguide/control-access.html)。

以下示例演示如何：
+ 使用列出密钥策略的名称[ListKeyPolicies](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-kms-2014-11-01.html#listkeypolicies)。
+ 使用获取密钥策略[GetKeyPolicy](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-kms-2014-11-01.html#getkeypolicy)。
+ 使用设置密钥策略[PutKeyPolicy](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-kms-2014-11-01.html#putkeypolicy)。

的所有示例代码都可以在[此 适用于 PHP 的 AWS SDK 处找到 GitHub](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)。

有关使用 AWS Key Management Service (AWS KMS) 的更多信息，请参阅《[AWS KMS 开发者指南》](https://docs.aws.amazon.com/kms/latest/developerguide/)。

## 列出所有密钥策略
<a name="list-all-key-policies"></a>

要获取 KMS 密钥的密钥策略名称，请使用 `ListKeyPolicies` 操作。

 **导入** 

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

use Aws\Exception\AwsException;
```

 **示例代码** 

```
$KmsClient = new Aws\Kms\KmsClient([
    'profile' => 'default',
    'version' => '2014-11-01',
    'region' => 'us-east-2'
]);

$keyId = 'arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab';
$limit = 10;

try {
    $result = $KmsClient->listKeyPolicies([
        'KeyId' => $keyId,
        'Limit' => $limit,
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    echo $e->getMessage();
    echo "\n";
}
```

## 检索密钥策略
<a name="retrieve-a-key-policy"></a>

要获取 KMS 密钥的密钥策略，请使用 `GetKeyPolicy` 操作。

 `GetKeyPolicy` 需要策略名称。除非您在创建 KMS 密钥时已创建密钥策略，否则，唯一有效的策略名称为默认值。要了解更多信息，请参阅 *AWS Key Management Service 开发人员指南*中的[默认密钥策略](https://docs.aws.amazon.com/kms/latest/developerguide/key-policy-default.html)。

 **导入** 

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

use Aws\Exception\AwsException;
```

 **示例代码** 

```
$KmsClient = new Aws\Kms\KmsClient([
    'profile' => 'default',
    'version' => '2014-11-01',
    'region' => 'us-east-2'
]);

$keyId = 'arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab';
$policyName = "default";

try {
    $result = $KmsClient->getKeyPolicy([
        'KeyId' => $keyId,
        'PolicyName' => $policyName
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    echo $e->getMessage();
    echo "\n";
}
```

## 设置密钥策略
<a name="set-a-key-policy"></a>

要为 KMS 密钥建立或更改密钥策略，请使用 `PutKeyPolicy` 操作。

 `PutKeyPolicy` 需要策略名称。除非您在创建 KMS 密钥时已创建密钥策略，否则，唯一有效的策略名称为默认值。要了解更多信息，请参阅 *AWS Key Management Service 开发人员指南*中的[默认密钥策略](https://docs.aws.amazon.com/kms/latest/developerguide/key-policy-default.html)。

 **导入** 

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

use Aws\Exception\AwsException;
```

 **示例代码** 

```
$KmsClient = new Aws\Kms\KmsClient([
    'profile' => 'default',
    'version' => '2014-11-01',
    'region' => 'us-east-2'
]);

$keyId = 'arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab';
$policyName = "default";

try {
    $result = $KmsClient->putKeyPolicy([
        'KeyId' => $keyId,
        'PolicyName' => $policyName,
        'Policy' => '{ 
            "Version":"2012-10-17",		 	 	  
            "Id": "custom-policy-2016-12-07", 
            "Statement": [ 
                { "Sid": "Enable IAM User Permissions", 
                "Effect": "Allow", 
                "Principal": 
                   { "AWS": "arn:aws:iam::111122223333:user/root" }, 
                "Action": [ "kms:*" ], 
                "Resource": "*" }, 
                { "Sid": "Enable IAM User Permissions", 
                "Effect": "Allow", 
                "Principal":                 
                   { "AWS": "arn:aws:iam::111122223333:user/ExampleUser" }, 
                "Action": [
                    "kms:Encrypt*",
                    "kms:GenerateDataKey*",
                    "kms:Decrypt*",
                    "kms:DescribeKey*",
                    "kms:ReEncrypt*"
                ], 
                "Resource": "*" }                 
            ]            
        } '
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    echo $e->getMessage();
    echo "\n";
}
```

# 使用 AWS KMS API 和 适用于 PHP 的 AWS SDK 版本 3 处理授权
<a name="kms-example-grants"></a>

授权 是提供权限的另一种机制。它是密钥策略的替代形式。您可以使用授权来授予长期访问权限，允许 AWS 委托人使用您的 AWS Key Management Service (AWS KMS) 客户[AWS KMS keys](https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#kms_keys)管理的权限。有关更多信息，请参阅 *AWS Key Management Service 开发人员指南*中的 [AWS KMS中的授权](https://docs.aws.amazon.com/kms/latest/developerguide/grants.html)。

以下示例演示如何：
+ 使用为 KMS 密钥创建授权[CreateGrant](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-kms-2014-11-01.html#creategrant)。
+ 使用查看 KMS 密钥的授权[ListGrants](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-kms-2014-11-01.html#listgrants)。
+ 使用取消对 KMS 密钥的授权[RetireGrant](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-kms-2014-11-01.html#retiregrant)。
+ 使用[RevokeGrant](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-kms-2014-11-01.html#revokegrant)撤销 KMS 密钥的授权。

的所有示例代码都可以在[此 适用于 PHP 的 AWS SDK 处找到 GitHub](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)。

有关使用 AWS Key Management Service (AWS KMS) 的更多信息，请参阅《[AWS KMS 开发者指南》](https://docs.aws.amazon.com/kms/latest/developerguide/)。

## 创建授权
<a name="create-a-grant"></a>

要为创建授权 AWS KMS key，请使用[CreateGrant](https://docs.aws.amazon.com/kms/latest/APIReference/API_CreateGrant.html)操作。

 **导入** 

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

use Aws\Exception\AwsException;
```

 **示例代码** 

```
$KmsClient = new Aws\Kms\KmsClient([
    'profile' => 'default',
    'version' => '2014-11-01',
    'region' => 'us-east-2'
]);

$keyId = 'arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab';
$granteePrincipal = "arn:aws:iam::111122223333:user/Alice";
$operation = ['Encrypt', 'Decrypt']; // A list of operations that the grant allows.

try {
    $result = $KmsClient->createGrant([
        'GranteePrincipal' => $granteePrincipal,
        'KeyId' => $keyId,
        'Operations' => $operation
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    echo $e->getMessage();
    echo "\n";
}
```

## 查看授权
<a name="view-a-grant"></a>

要获取有关授予的详细信息 AWS KMS key，请使用[ListGrants](https://docs.aws.amazon.com/kms/latest/APIReference/API_ListGrants.html)操作。

 **导入** 

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

use Aws\Exception\AwsException;
```

 **示例代码** 

```
$KmsClient = new Aws\Kms\KmsClient([
    'profile' => 'default',
    'version' => '2014-11-01',
    'region' => 'us-east-2'
]);

$keyId = 'arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab';
$limit = 10;

try {
    $result = $KmsClient->listGrants([
        'KeyId' => $keyId,
        'Limit' => $limit,
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    echo $e->getMessage();
    echo "\n";
}
```

## 停用授权
<a name="retire-a-grant"></a>

要取消的授权 AWS KMS key，请使用[RetireGrant](https://docs.aws.amazon.com/kms/latest/APIReference/API_RetireGrant.html)操作。在使用完授权后，请停用授权以将其清除。

 **导入** 

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

use Aws\Exception\AwsException;
```

 **示例代码** 

```
$KmsClient = new Aws\Kms\KmsClient([
    'profile' => 'default',
    'version' => '2014-11-01',
    'region' => 'us-east-2'
]);

$grantToken = 'Place your grant token here';

try {
    $result = $KmsClient->retireGrant([
        'GrantToken' => $grantToken,
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    echo $e->getMessage();
    echo "\n";
}

//Can also identify grant to retire by a combination of the grant ID
//and the Amazon Resource Name (ARN) of the customer master key (CMK)
$keyId = 'arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab';
$grantId = 'Unique identifier of the grant returned during CreateGrant operation';

try {
    $result = $KmsClient->retireGrant([
        'GrantId' => $grantToken,
        'KeyId' => $keyId,
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    echo $e->getMessage();
    echo "\n";
}
```

## 撤销授权
<a name="revoke-a-grant"></a>

要撤消对的授权 AWS KMS key，请使用[RevokeGrant](https://docs.aws.amazon.com/kms/latest/APIReference/API_RevokeGrant.html)操作。您可以撤销授予，以显式拒绝依赖它的操作。

 **导入** 

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

use Aws\Exception\AwsException;
```

 **示例代码** 

```
$KmsClient = new Aws\Kms\KmsClient([
    'profile' => 'default',
    'version' => '2014-11-01',
    'region' => 'us-east-2'
]);

$keyId = 'arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab';
$grantId = "grant1";

try {
    $result = $KmsClient->revokeGrant([
        'KeyId' => $keyId,
        'GrantId' => $grantId,
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    echo $e->getMessage();
    echo "\n";
}
```

# 使用 AWS KMS API 和 适用于 PHP 的 AWS SDK 版本 3 处理别名
<a name="kms-example-alias"></a>

AWS Key Management Service (AWS KMS) 为[AWS KMS key](https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#kms_keys)被叫的别名提供可选的显示名称。

以下示例演示如何：
+ 使用创建别名[CreateAlias](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-kms-2014-11-01.html#createalias)。
+ 使用查看别名[ListAliases](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-kms-2014-11-01.html#listaliases)。
+ 使用更新别名[UpdateAlias](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-kms-2014-11-01.html#updatealias)。
+ 使用删除别名[DeleteAlias](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-kms-2014-11-01.html#deletealias)。

的所有示例代码都可以在[此 适用于 PHP 的 AWS SDK 处找到 GitHub](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)。

有关使用 AWS Key Management Service (AWS KMS) 的更多信息，请参阅《[AWS KMS 开发者指南》](https://docs.aws.amazon.com/kms/latest/developerguide/)。

## 创建 别名
<a name="create-an-alias"></a>

要为 KMS 密钥创建别名，请使用[CreateAlias](https://docs.aws.amazon.com/kms/latest/APIReference/API_CreateAlias.html)操作。别名在账户和 AWS 地区中必须是唯一的。如果为已有别名的 KMS 密钥创建别名，`CreateAlias` 会为同一 KMS 密钥创建另一个别名。它不会替换现有别名。

 **导入** 

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

use Aws\Exception\AwsException;
```

 **示例代码** 

```
$KmsClient = new Aws\Kms\KmsClient([
    'profile' => 'default',
    'version' => '2014-11-01',
    'region' => 'us-east-2'
]);

$keyId = 'arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab';
$aliasName = "alias/projectKey1";

try {
    $result = $KmsClient->createAlias([
        'AliasName' => $aliasName,
        'TargetKeyId' => $keyId,
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    echo $e->getMessage();
    echo "\n";
}
```

## 查看别名
<a name="view-an-alias"></a>

要列出调用方 AWS 账户 和中的所有别名 AWS 区域，请使用[ListAliases](https://docs.aws.amazon.com/kms/latest/APIReference/API_ListAliases.html)操作。

 **导入** 

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

use Aws\Exception\AwsException;
```

 **示例代码** 

```
$KmsClient = new Aws\Kms\KmsClient([
    'profile' => 'default',
    'version' => '2014-11-01',
    'region' => 'us-east-2'
]);

$limit = 10;

try {
    $result = $KmsClient->listAliases([
        'Limit' => $limit,
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    echo $e->getMessage();
    echo "\n";
}
```

## 更新别名
<a name="update-an-alias"></a>

要将现有别名与其他 KMS 密钥关联，请使用[UpdateAlias](https://docs.aws.amazon.com/kms/latest/APIReference/API_UpdateAlias.html)操作。

 **导入** 

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

use Aws\Exception\AwsException;
```

 **示例代码** 

```
$KmsClient = new Aws\Kms\KmsClient([
    'profile' => 'default',
    'version' => '2014-11-01',
    'region' => 'us-east-2'
]);

$keyId = 'arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab';
$aliasName = "alias/projectKey1";

try {
    $result = $KmsClient->updateAlias([
        'AliasName' => $aliasName,
        'TargetKeyId' => $keyId,
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    echo $e->getMessage();
    echo "\n";
}
```

## 删除别名
<a name="delete-an-alias"></a>

要删除别名，请使用[DeleteAlias](https://docs.aws.amazon.com/kms/latest/APIReference/API_DeleteAlias.html)操作。删除别名不会影响底层 KMS 密钥。

 **导入** 

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

use Aws\Exception\AwsException;
```

 **示例代码** 

```
$KmsClient = new Aws\Kms\KmsClient([
    'profile' => 'default',
    'version' => '2014-11-01',
    'region' => 'us-east-2'
]);

$aliasName = "alias/projectKey1";

try {
    $result = $KmsClient->deleteAlias([
        'AliasName' => $aliasName,
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    echo $e->getMessage();
    echo "\n";
}
```

# 使用 适用于 PHP 的 AWS SDK 版本 3 的 Amazon Kinesis 示例
<a name="kinesis-examples"></a>

Amazon Kinesis 是一项 AWS 服务，可实时收集、处理和分析数据。使用 Amazon Kinesis Data Streams 来配置数据流，或者使用 Amazon Data Firehose 来将数据发送到 Amazon S3、OpenSearch Service、Amazon Redshift 或 Splunk。

有关 Kinesis 的更多信息，请参阅 [Amazon Kinesis 文档](https://docs.aws.amazon.com/kinesis/index.html)。

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

**Topics**
+ [Kinesis Data Streams](kinesis-example-data-stream.md)
+ [Kinesis 分片](kinesis-example-shard.md)
+ [Kinesis Data Firehose 传输流](kinesis-firehose-example-delivery-stream.md)

# 使用 Kinesis Data Streams API 和 适用于 PHP 的 AWS SDK 版本 3 来创建数据流
<a name="kinesis-example-data-stream"></a>

Amazon Kinesis Data Streams 允许发送实时数据。使用 Kinesis Data Streams 来创建数据创建器，该创建器在每次添加数据时将数据发送到配置的目的地。

有关更多信息，请参阅 Amazon Kinesis 开发人员指南中的[创建和管理流](https://docs.aws.amazon.com/kinesis/latest/dev/working-with-streams.html.html)。

以下示例演示如何：
+ 使用 [CreateAlias](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-kinesis-1913-12-02.html#createstream) 创建数据流。
+ 使用 [DescribeStream](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-kinesis-1913-12-02.html#describestream) 获取有关单个数据流的详细信息。
+ 使用 [ListStreams](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-kinesis-1913-12-02.html#liststreams) 列出现有数据流。
+ 使用 [PutRecord](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-kinesis-1913-12-02.html#putrecord) 将数据发送到现有数据流。
+ 使用 [DeleteStream](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-kinesis-1913-12-02.html#deletestream) 删除数据流。

适用于 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) 中所述。

有关使用 Amazon Kinesis 开发人员指南的更多信息，请参阅 [Amazon Kinesis Data Streams 开发人员指南](https://docs.aws.amazon.com/kinesis/latest/dev/)。

## 使用 Kinesis 数据流来创建数据流
<a name="create-a-data-stream-using-a-ak-data-stream"></a>

建立 Kinesis 数据流，您可以使用以下代码示例来在其中发送要由 Kinesis 处理的信息。要了解更多信息，请参阅 Amazon Kinesis 开发人员指南中的[创建和更新数据流](https://docs.aws.amazon.com/kinesis/latest/dev/amazon-kinesis-streams.html)。

要创建 Kinesis 数据流，请使用 [CreateStream](https://docs.aws.amazon.com/kinesis/latest/APIReference/API_CreateStream.html) 操作。

 **导入**。

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

use Aws\Exception\AwsException;
```

 **示例代码** 

```
$kinesisClient = new Aws\Kinesis\KinesisClient([
    'profile' => 'default',
    'version' => '2013-12-02',
    'region' => 'us-east-2'
]);

$shardCount = 2;
$name = "my_stream_name";

try {
    $result = $kinesisClient->createStream([
        'ShardCount' => $shardCount,
        'StreamName' => $name,
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    echo $e->getMessage();
    echo "\n";
}
```

## 检索数据流
<a name="retrieve-a-data-stream"></a>

获取有关使用以下代码示例的现有数据流的详细信息。默认情况下，这将返回有关连接到指定 Kinesis 数据流的前 10 个分片的信息。在将数据写入 Kinesis 数据流之前，请记住检查响应中的 `StreamStatus`。

要检索有关指定 Kinesis 数据流的详细信息，请使用 [DescribeStream](https://docs.aws.amazon.com/kinesis/latest/APIReference/API_DescribeStream.html) 操作。

 **导入**。

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

use Aws\Exception\AwsException;
```

 **示例代码** 

```
$kinesisClient = new Aws\Kinesis\KinesisClient([
    'profile' => 'default',
    'version' => '2013-12-02',
    'region' => 'us-east-2'
]);

$name = "my_stream_name";

try {
    $result = $kinesisClient->describeStream([
        'StreamName' => $name,
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    echo $e->getMessage();
    echo "\n";
}
```

## 列出已连接到 Kinesis 的现有数据流
<a name="list-existing-data-streams-that-are-connected-to-ak"></a>

列出所选 AWS 区域中您 AWS 账户 的前 10 个数据流。使用返回的 ``HasMoreStreams` 来确定是否有更多与您的账户关联的流。

要列出 Kinesis 数据流，请使用 [ListStreams](https://docs.aws.amazon.com/kinesis/latest/APIReference/API_ListStreams.html) 操作。

 **导入**。

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

use Aws\Exception\AwsException;
```

 **示例代码** 

```
$kinesisClient = new Aws\Kinesis\KinesisClient([
    'profile' => 'default',
    'version' => '2013-12-02',
    'region' => 'us-east-2'
]);

try {
    $result = $kinesisClient->listStreams();
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    echo $e->getMessage();
    echo "\n";
}
```

## 将数据发送到现有数据流
<a name="send-data-to-an-existing-data-stream"></a>

在创建数据流后，请使用以下示例来发送数据。在向其发送数据之前，请使用 `DescribeStream` 检查数据 `StreamStatus` 是否处于活动状态。

要将单条数据记录写入 Kinesis 数据流，请使用 [PutRecord](https://docs.aws.amazon.com/kinesis/latest/APIReference/API_PutRecord.html) 操作。要将最多 500 条记录写入 Kinesis 数据流，请使用 [PutRecords](https://docs.aws.amazon.com/kinesis/latest/APIReference/API_PutRecords.html) 操作。

 **导入**。

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

use Aws\Exception\AwsException;
```

 **示例代码** 

```
$kinesisClient = new Aws\Kinesis\KinesisClient([
    'profile' => 'default',
    'version' => '2013-12-02',
    'region' => 'us-east-1'
]);

$name = "my_stream_name";
$content = '{"ticker_symbol":"QXZ", "sector":"HEALTHCARE", "change":-0.05, "price":84.51}';
$groupID = "input to a hash function that maps the partition key (and associated data) to a specific shard";

try {
    $result = $kinesisClient->PutRecord([
        'Data' => $content,
        'StreamName' => $name,
        'PartitionKey' => $groupID
    ]);
    print("<p>ShardID = " . $result["ShardId"] . "</p>");
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    echo $e->getMessage();
    echo "\n";
}
```

## 删除数据流
<a name="delete-a-data-stream"></a>

此示例演示如何删除数据流。删除数据流也会删除您发送到数据流的所有数据。活动 Kinesis 数据流切换到 DELETING 状态，直到完成流删除操作。在处于 DELETING 状态时，流将继续处理数据。

要删除 Kinesis 数据流，请使用 [DeleteStream](https://docs.aws.amazon.com/kinesis/latest/APIReference/API_DeleteStream.html) 操作。

 **导入**。

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

use Aws\Exception\AwsException;
```

 **示例代码** 

```
$kinesisClient = new Aws\Kinesis\KinesisClient([
    'profile' => 'default',
    'version' => '2013-12-02',
    'region' => 'us-east-2'
]);

$name = "my_stream_name";

try {
    $result = $kinesisClient->deleteStream([
        'StreamName' => $name,
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    echo $e->getMessage();
    echo "\n";
}
```

# 使用 Kinesis Data Streams API 和 适用于 PHP 的 AWS SDK 版本 3 来管理数据分片
<a name="kinesis-example-shard"></a>

Amazon Kinesis Data Streams 允许向端点发送实时数据。数据流的速率取决于流中的分片数。

您可以每秒向单个分片写入 1000 条记录。每个分片的上传限制为每秒 1 MiB。用量按每个分片计算和收费，因此，请使用这些示例来管理流的数据容量和成本。

以下示例演示如何：
+ 使用 [ListShards](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-kinesis-1913-12-02.html#listshards) 列出流中的分片。
+ 使用 [UpdateShardCount](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-kinesis-1913-12-02.html#updateshardcount) 增加或减少流中的分片数。

适用于 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) 中所述。

有关使用 Amazon Kinesis Data Streams 的更多信息，请参阅 [Amazon Kinesis Data Streams 开发人员指南](https://docs.aws.amazon.com/streams/latest/dev/)。

## 列出数据流分片
<a name="list-data-stream-shards"></a>

列出特定流中最多 100 个分片的详细信息。

要列出 Kinesis 数据流中的分片，请使用 [ListShards](https://docs.aws.amazon.com/kinesis/latest/APIReference/API_ListShards.html) 操作。

 **导入**。

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

use Aws\Exception\AwsException;
```

 **示例代码** 

```
$kinesisClient = new Aws\Kinesis\KinesisClient([
    'profile' => 'default',
    'version' => '2013-12-02',
    'region' => 'us-east-2'
]);

$name = "my_stream_name";

try {
    $result = $kinesisClient->ListShards([
        'StreamName' => $name,
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    echo $e->getMessage();
    echo "\n";
}
```

## 添加更多数据流分片
<a name="add-more-data-stream-shards"></a>

如果您需要更多数据流分片，则可增加当前分片数。我们建议您在增加时使分片计数加倍。这将生成当前可用的每个分片的副本以增加容量。在一个 24 小时的期间内，您只能将分片数加倍两次。

请记住，Kinesis Data Streams 用量的费用是按分片计算的，因此当需求减少时，我们建议将分片数量减半。删除分片时，只能将分片数量减少到当前分片计数的一半。

要更新 Kinesis 数据流的分片数，请使用 [UpdateShardCount](https://docs.aws.amazon.com/kinesis/latest/APIReference/API_UpdateShardCount.html) 操作。

 **导入**。

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

use Aws\Exception\AwsException;
```

 **示例代码** 

```
$kinesisClient = new Aws\Kinesis\KinesisClient([
    'profile' => 'default',
    'version' => '2013-12-02',
    'region' => 'us-east-2'
]);

$name = "my_stream_name";
$totalshards = 4;

try {
    $result = $kinesisClient->UpdateShardCount([
        'ScalingType' => 'UNIFORM_SCALING',
        'StreamName' => $name,
        'TargetShardCount' => $totalshards
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    echo $e->getMessage();
    echo "\n";
}
```

# 使用 Firehose API 和适用于 PHP 的 AWS SDK 版本 3 来创建传输流
<a name="kinesis-firehose-example-delivery-stream"></a>

Amazon Data Firehose 支持将实时数据发送到其他 AWS 服务，包括 Amazon Kinesis Data Streams、Amazon S3、Amazon OpenSearch Service（OpenSearch Service）和 Amazon Redshift，或者发送到 Splunk。使用传输流创建一个数据创建器，以在您每次添加数据时将数据传送到配置的目的地。

以下示例演示如何：
+ 使用 [CreateDeliveryStream](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-firehose-2015-08-04.html#createdeliverystream) 创建传输流。
+ 使用 [DescribeDeliveryStream](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-firehose-2015-08-04.html#describedeliverystream) 获取有关单个传输流的详细信息。
+ 使用 [ListDeliveryStreams](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-firehose-2015-08-04.html#listdeliverystreams) 列出传输流。
+ 使用 [PutRecord](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-firehose-2015-08-04.html#putrecord) 将数据发送到传输流。
+ 使用 [DeleteDeliveryStream](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-firehose-2015-08-04.html#deletedeliverystream) 删除传输流。

适用于 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) 中所述。

有关使用 Amazon Data Firehose 的更多信息，请参阅 [Amazon Kinesis Data Firehose 开发人员指南](https://docs.aws.amazon.com/streams/latest/dev/)。

## 使用 Kinesis 数据流来创建传输流
<a name="create-a-delivery-stream-using-a-ak-data-stream"></a>

要建立将数据放入现有 Kinesis 数据流的传输流，请使用 [CreateDeliveryStream](https://docs.aws.amazon.com/firehose/latest/APIReference/API_CreateDeliveryStream.html) 操作。

这使开发人员能够将现有 Kinesis 服务迁移到 Firehose。

 **导入** 

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

use Aws\Exception\AwsException;
```

 **示例代码** 

```
$firehoseClient = new Aws\Firehose\FirehoseClient([
    'profile' => 'default',
    'version' => '2015-08-04',
    'region' => 'us-east-2'
]);

$name = "my_stream_name";
$stream_type = "KinesisStreamAsSource";
$kinesis_stream = "arn:aws:kinesis:us-east-2:0123456789:stream/my_stream_name";
$role = "arn:aws:iam::0123456789:policy/Role";

try {
    $result = $firehoseClient->createDeliveryStream([
        'DeliveryStreamName' => $name,
        'DeliveryStreamType' => $stream_type,
        'KinesisStreamSourceConfiguration' => [
            'KinesisStreamARN' => $kinesis_stream,
            'RoleARN' => $role,
        ],
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    echo $e->getMessage();
    echo "\n";
}
```

## 使用 Amazon S3 存储桶来创建传输流
<a name="create-a-delivery-stream-using-an-s3-bucket"></a>

要建立将数据放入现有 Amazon S3 存储桶的传输流，请使用 [CreateDeliveryStream](https://docs.aws.amazon.com/firehose/latest/APIReference/API_CreateDeliveryStream.html) 操作。

提供目标参数，如[目标参数](https://docs.aws.amazon.com/firehose/latest/dev/create-destination.html)中所述。然后，确保向 Firehose 授予访问 Amazon S3 存储桶的权限，如[向 Kinesis Data Firehose 授予访问 Amazon S3 目标的权限](https://docs.aws.amazon.com/firehose/latest/dev/controlling-access.html#using-iam-s3.html)中所述。

 **导入** 

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

use Aws\Exception\AwsException;
```

 **示例代码** 

```
$firehoseClient = new Aws\Firehose\FirehoseClient([
    'profile' => 'default',
    'version' => '2015-08-04',
    'region' => 'us-east-2'
]);

$name = "my_S3_stream_name";
$stream_type = "DirectPut";
$s3bucket = 'arn:aws:s3:::bucket_name';
$s3Role = 'arn:aws:iam::0123456789:policy/Role';

try {
    $result = $firehoseClient->createDeliveryStream([
        'DeliveryStreamName' => $name,
        'DeliveryStreamType' => $stream_type,
        'S3DestinationConfiguration' => [
            'BucketARN' => $s3bucket,
            'CloudWatchLoggingOptions' => [
                'Enabled' => false,
            ],
            'RoleARN' => $s3Role
        ],
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    echo $e->getMessage();
    echo "\n";
}
```

## 使用 OpenSearch Service 来创建传输流
<a name="create-a-delivery-stream-using-es"></a>

要建立将数据放入 OpenSearch Service 集群的 Firehose 传输流，请使用 [CreateDeliveryStream](https://docs.aws.amazon.com/firehose/latest/APIReference/API_CreateDeliveryStream.html) 操作。

提供目标参数，如[目标参数](https://docs.aws.amazon.com/firehose/latest/dev/create-destination.html)中所述。确保向 Firehose 授予访问 OpenSearch Service 集群的权限，如[向 Kinesis Data Firehose 授予访问 Amazon ES 目标的权限](https://docs.aws.amazon.com/firehose/latest/dev/controlling-access.html#using-iam-es.html)中所述。

 **导入** 

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

use Aws\Exception\AwsException;
```

 **示例代码** 

```
$firehoseClient = new Aws\Firehose\FirehoseClient([
    'profile' => 'default',
    'version' => '2015-08-04',
    'region' => 'us-east-2'
]);

$name = "my_ES_stream_name";
$stream_type = "DirectPut";
$esDomainARN = 'arn:aws:es:us-east-2:0123456789:domain/Name';
$esRole = 'arn:aws:iam::0123456789:policy/Role';
$esIndex = 'root';
$esType = 'PHP_SDK';
$s3bucket = 'arn:aws:s3:::bucket_name';
$s3Role = 'arn:aws:iam::0123456789:policy/Role';

try {
    $result = $firehoseClient->createDeliveryStream([
        'DeliveryStreamName' => $name,
        'DeliveryStreamType' => $stream_type,
        'ElasticsearchDestinationConfiguration' => [
            'DomainARN' => $esDomainARN,
            'IndexName' => $esIndex,
            'RoleARN' => $esRole,
            'S3Configuration' => [
                'BucketARN' => $s3bucket,
                'CloudWatchLoggingOptions' => [
                    'Enabled' => false,
                ],
                'RoleARN' => $s3Role,
            ],
            'TypeName' => $esType,
        ],
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    echo $e->getMessage();
    echo "\n";
}
```

## 检索传输流
<a name="retrieve-a-delivery-stream"></a>

要获取有关现有 Firehose 传输流的详细信息，请使用 [DescribeDeliveryStream](https://docs.aws.amazon.com/firehose/latest/APIReference/API_DescribeDeliveryStream.html) 操作。

 **导入** 

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

use Aws\Exception\AwsException;
```

 **示例代码** 

```
$firehoseClient = new Aws\Firehose\FirehoseClient([
    'profile' => 'default',
    'version' => '2015-08-04',
    'region' => 'us-east-2'
]);

$name = "my_stream_name";

try {
    $result = $firehoseClient->describeDeliveryStream([
        'DeliveryStreamName' => $name,
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    echo $e->getMessage();
    echo "\n";
}
```

## 列出已连接到 Kinesis Data Streams 的现有传输流
<a name="list-existing-delivery-streams-connected-to-aks"></a>

要列出所有将数据发送到 Kinesis Data Streams 的现有 Firehose 传输流，请使用 [ListDeliveryStreams](https://docs.aws.amazon.com/firehose/latest/APIReference/API_ListDeliveryStreams.html) 操作。

 **导入**。

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

use Aws\Exception\AwsException;
```

 **示例代码** 

```
$firehoseClient = new Aws\Firehose\FirehoseClient([
    'profile' => 'default',
    'version' => '2015-08-04',
    'region' => 'us-east-2'
]);

try {
    $result = $firehoseClient->listDeliveryStreams([
        'DeliveryStreamType' => 'KinesisStreamAsSource',
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    echo $e->getMessage();
    echo "\n";
}
```

## 列出将数据发送到其他 AWS 服务的现有传输流
<a name="list-existing-delivery-streams-sending-data-to-other-aws-services"></a>

要列出所有将数据发送到 Amazon S3、OpenSearch Service、Amazon Redshift，或者发送到 Splunk 的现有 Firehose 传输流，请使用 [ListDeliveryStreams](https://docs.aws.amazon.com/firehose/latest/APIReference/API_ListDeliveryStreams.html) 操作。

 **导入** 

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

use Aws\Exception\AwsException;
```

 **示例代码** 

```
$firehoseClient = new Aws\Firehose\FirehoseClient([
    'profile' => 'default',
    'version' => '2015-08-04',
    'region' => 'us-east-2'
]);

try {
    $result = $firehoseClient->listDeliveryStreams([
        'DeliveryStreamType' => 'DirectPut',
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    echo $e->getMessage();
    echo "\n";
}
```

## 将数据发送到现有 Firehose 传输流
<a name="send-data-to-an-existing-akf-delivery-stream"></a>

要通过 Firehose 传输流将数据发送到指定目的地，请在创建 Firehose 传输流之后使用 [PutRecord](https://docs.aws.amazon.com/firehose/latest/APIReference/API_API_PutRecord.html) 操作。

在将数据发送到 Firehose 传输流之前，请使用 `DescribeDeliveryStream` 来了解该传输流是否处于活动状态。

 **导入** 

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

use Aws\Exception\AwsException;
```

 **示例代码** 

```
$firehoseClient = new Aws\Firehose\FirehoseClient([
    'profile' => 'default',
    'version' => '2015-08-04',
    'region' => 'us-east-2'
]);

$name = "my_stream_name";
$content = '{"ticker_symbol":"QXZ", "sector":"HEALTHCARE", "change":-0.05, "price":84.51}';

try {
    $result = $firehoseClient->putRecord([
        'DeliveryStreamName' => $name,
        'Record' => [
            'Data' => $content,
        ],
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    echo $e->getMessage();
    echo "\n";
}
```

## 删除 Firehose 传输流
<a name="delete-a-akf-delivery-stream"></a>

要删除 Firehose 传输流，请使用 [DeleteDeliveryStreams](https://docs.aws.amazon.com/firehose/latest/APIReference/API_DeleteDeliveryStreams.html) 操作。这也将删除您已发送到该传输流的所有数据。

 **导入** 

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

use Aws\Exception\AwsException;
```

 **示例代码** 

```
$firehoseClient = new Aws\Firehose\FirehoseClient([
    'profile' => 'default',
    'version' => '2015-08-04',
    'region' => 'us-east-2'
]);

$name = "my_stream_name";

try {
    $result = $firehoseClient->deleteDeliveryStream([
        'DeliveryStreamName' => $name,
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    echo $e->getMessage();
    echo "\n";
}
```

# AWS Elemental MediaConvert 使用 适用于 PHP 的 AWS SDK 版本 3 的示例
<a name="emc-examples"></a>

AWS Elemental MediaConvert 是一种基于文件的视频转码服务，具有广播级功能。您可以使用它来创建用于通过互联网进行广播和 video-on-demand（VOD）交付的资产。有关更多信息，请参阅 [AWS Elemental MediaConvert 《用户指南》](https://docs.aws.amazon.com/mediaconvert/latest/ug/)。

的 PHP API 通过*`AWS.MediaConvert`*客户端类公开。 AWS Elemental MediaConvert 有关更多信息，请参阅《 API 参考》中的 [https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-mediaconvert-2017-08-29.html](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-mediaconvert-2017-08-29.html)。

## 在中创建和管理转码作业 AWS Elemental MediaConvert
<a name="emc-examples-jobs"></a>

在此示例中，您使用 适用于 PHP 的 AWS SDK 版本 3 调用 AWS Elemental MediaConvert 和创建转码作业。在开始之前，您需要将输入视频上传到为输入存储预配置的 Amazon S3 存储桶。有关支持的输入视频编解码器和容器的列表，请参阅 [AWS Elemental MediaConvert 用户指南](https://docs.aws.amazon.com/mediaconvert/latest/ug/)中的[支持的输入编解码器和容器](https://docs.aws.amazon.com/mediaconvert/latest/ug/reference-codecs-containers-input.html)。

以下示例演示如何：
+ 在中创建转码任务。 AWS Elemental MediaConvert[CreateJob](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-mediaconvert-2017-08-29.html#createjob)。
+ 取消 AWS Elemental MediaConvert 队列中的转码作业。 [CancelJob](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-mediaconvert-2017-08-29.html#canceljob)
+ 检索已完成的转码任务的 JSON。 [GetJob](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-mediaconvert-2017-08-29.html#getjob)
+ 检索最多 20 个最近创建的任务的 JSON 数组。 [ListJobs](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-mediaconvert-2017-08-29.html#listjobs)

的所有示例代码都可以在[此 适用于 PHP 的 AWS SDK 处找到 GitHub](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)。

要访问 MediaConvert 客户端，请创建一个 IAM 角色来 AWS Elemental MediaConvert 访问您的输入文件和存储输出文件的 Amazon S3 存储桶。有关更多信息，请参阅 [AWS Elemental MediaConvert 用户指南](https://docs.aws.amazon.com/mediaconvert/latest/ug/)中的[设置 IAM 权限](https://docs.aws.amazon.com/mediaconvert/latest/ug/iam-role.html)。

### 创建客户端
<a name="create-a-client"></a>

 适用于 PHP 的 AWS SDK 通过创建 MediaConvert 客户端进行配置，其中包含您的代码所在的区域。在本示例中，区域设置为 us-west-2。

 **导入** 

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

use Aws\Exception\AwsException;
use Aws\MediaConvert\MediaConvertClient;
```

 **示例代码** 

```
$mediaConvertClient = new MediaConvertClient([
    'version' => '2017-08-29',
    'region' => 'us-east-2',
    'profile' => 'default'
]);
```

### 定义简单的转码任务
<a name="defining-a-simple-transcoding-job"></a>

创建定义转码任务参数的 JSON。

这些参数有详细说明。您可以使用 [AWS Elemental MediaConvert 控制台](https://console.aws.amazon.com/mediaconvert/home)生成 JSON 作业参数，方法是在控制台中选择您的作业设置，然后选择**作业**部分底部的**显示作业 JSON**。本示例说明了简单作业的 JSON。

 **示例代码** 

```
$jobSetting = [
    "OutputGroups" => [
        [
            "Name" => "File Group",
            "OutputGroupSettings" => [
                "Type" => "FILE_GROUP_SETTINGS",
                "FileGroupSettings" => [
                    "Destination" => "s3://OUTPUT_BUCKET_NAME/"
                ]
            ],
            "Outputs" => [
                [
                    "VideoDescription" => [
                        "ScalingBehavior" => "DEFAULT",
                        "TimecodeInsertion" => "DISABLED",
                        "AntiAlias" => "ENABLED",
                        "Sharpness" => 50,
                        "CodecSettings" => [
                            "Codec" => "H_264",
                            "H264Settings" => [
                                "InterlaceMode" => "PROGRESSIVE",
                                "NumberReferenceFrames" => 3,
                                "Syntax" => "DEFAULT",
                                "Softness" => 0,
                                "GopClosedCadence" => 1,
                                "GopSize" => 90,
                                "Slices" => 1,
                                "GopBReference" => "DISABLED",
                                "SlowPal" => "DISABLED",
                                "SpatialAdaptiveQuantization" => "ENABLED",
                                "TemporalAdaptiveQuantization" => "ENABLED",
                                "FlickerAdaptiveQuantization" => "DISABLED",
                                "EntropyEncoding" => "CABAC",
                                "Bitrate" => 5000000,
                                "FramerateControl" => "SPECIFIED",
                                "RateControlMode" => "CBR",
                                "CodecProfile" => "MAIN",
                                "Telecine" => "NONE",
                                "MinIInterval" => 0,
                                "AdaptiveQuantization" => "HIGH",
                                "CodecLevel" => "AUTO",
                                "FieldEncoding" => "PAFF",
                                "SceneChangeDetect" => "ENABLED",
                                "QualityTuningLevel" => "SINGLE_PASS",
                                "FramerateConversionAlgorithm" => "DUPLICATE_DROP",
                                "UnregisteredSeiTimecode" => "DISABLED",
                                "GopSizeUnits" => "FRAMES",
                                "ParControl" => "SPECIFIED",
                                "NumberBFramesBetweenReferenceFrames" => 2,
                                "RepeatPps" => "DISABLED",
                                "FramerateNumerator" => 30,
                                "FramerateDenominator" => 1,
                                "ParNumerator" => 1,
                                "ParDenominator" => 1
                            ]
                        ],
                        "AfdSignaling" => "NONE",
                        "DropFrameTimecode" => "ENABLED",
                        "RespondToAfd" => "NONE",
                        "ColorMetadata" => "INSERT"
                    ],
                    "AudioDescriptions" => [
                        [
                            "AudioTypeControl" => "FOLLOW_INPUT",
                            "CodecSettings" => [
                                "Codec" => "AAC",
                                "AacSettings" => [
                                    "AudioDescriptionBroadcasterMix" => "NORMAL",
                                    "RateControlMode" => "CBR",
                                    "CodecProfile" => "LC",
                                    "CodingMode" => "CODING_MODE_2_0",
                                    "RawFormat" => "NONE",
                                    "SampleRate" => 48000,
                                    "Specification" => "MPEG4",
                                    "Bitrate" => 64000
                                ]
                            ],
                            "LanguageCodeControl" => "FOLLOW_INPUT",
                            "AudioSourceName" => "Audio Selector 1"
                        ]
                    ],
                    "ContainerSettings" => [
                        "Container" => "MP4",
                        "Mp4Settings" => [
                            "CslgAtom" => "INCLUDE",
                            "FreeSpaceBox" => "EXCLUDE",
                            "MoovPlacement" => "PROGRESSIVE_DOWNLOAD"
                        ]
                    ],
                    "NameModifier" => "_1"
                ]
            ]
        ]
    ],
    "AdAvailOffset" => 0,
    "Inputs" => [
        [
            "AudioSelectors" => [
                "Audio Selector 1" => [
                    "Offset" => 0,
                    "DefaultSelection" => "NOT_DEFAULT",
                    "ProgramSelection" => 1,
                    "SelectorType" => "TRACK",
                    "Tracks" => [
                        1
                    ]
                ]
            ],
            "VideoSelector" => [
                "ColorSpace" => "FOLLOW"
            ],
            "FilterEnable" => "AUTO",
            "PsiControl" => "USE_PSI",
            "FilterStrength" => 0,
            "DeblockFilter" => "DISABLED",
            "DenoiseFilter" => "DISABLED",
            "TimecodeSource" => "EMBEDDED",
            "FileInput" => "s3://INPUT_BUCKET_AND_FILE_NAME"
        ]
    ],
    "TimecodeConfig" => [
        "Source" => "EMBEDDED"
    ]
];
```

### 创建作业
<a name="create-a-job"></a>

在创建任务参数 JSON 后，通过调用 `AWS.MediaConvert service object` 并传递参数，来调用 createJob 方法。所创建任务的 ID 在响应数据中返回。

 **示例代码** 

```
try {
    $result = $mediaConvertClient->createJob([
        "Role" => "IAM_ROLE_ARN",
        "Settings" => $jobSetting, //JobSettings structure
        "Queue" => "JOB_QUEUE_ARN",
        "UserMetadata" => [
            "Customer" => "Amazon"
        ],
    ]);
} catch (AwsException $e) {
    // output error message if fails
    echo $e->getMessage();
    echo "\n";
}
```

### 检索任务
<a name="retrieve-a-job"></a>

使用在调用 createjob 时返回的 JobID，您可以获取最近任务的 JSON 格式的详细描述。

 **示例代码** 

```
$mediaConvertClient = new MediaConvertClient([
    'version' => '2017-08-29',
    'region' => 'us-east-2',
    'profile' => 'default'
]);

try {
    $result = $mediaConvertClient->getJob([
        'Id' => 'JOB_ID',
    ]);
} catch (AwsException $e) {
    // output error message if fails
    echo $e->getMessage();
    echo "\n";
}
```

### 取消任务
<a name="cancel-a-job"></a>

使用在调用 createjob 时返回的 JobID，您可以取消仍在队列中的任务。您无法取消已开始转码的任务。

 **示例代码** 

```
$mediaConvertClient = new MediaConvertClient([
    'version' => '2017-08-29',
    'region' => 'us-east-2',
    'profile' => 'default'
]);

try {
    $result = $mediaConvertClient->cancelJob([
        'Id' => 'JOB_ID', // REQUIRED The Job ID of the job to be cancelled.
    ]);
} catch (AwsException $e) {
    // output error message if fails
    echo $e->getMessage();
    echo "\n";
}
```

### 列出最近的转码任务
<a name="listing-recent-transcoding-jobs"></a>

创建包括值的参数 JSON，以指定是按升序还是降序对列表排序，要检查的任务队列的 ARN，以及要包含的任务的状态。这将返回最多 20 个任务。要检索后面的 20 个最近任务，请使用随结果返回的 nextToken 字符串。

 **示例代码** 

```
$mediaConvertClient = new MediaConvertClient([
    'version' => '2017-08-29',
    'region' => 'us-east-2',
    'profile' => 'default'
]);

try {
    $result = $mediaConvertClient->listJobs([
        'MaxResults' => 20,
        'Order' => 'ASCENDING',
        'Queue' => 'QUEUE_ARN',
        'Status' => 'SUBMITTED',
        // 'NextToken' => '<string>', //OPTIONAL To retrieve the twenty next most recent jobs
    ]);
} catch (AwsException $e) {
    // output error message if fails
    echo $e->getMessage();
    echo "\n";
}
```

# 使用 适用于 PHP 的 AWS SDK 版本 3 的 Amazon S3 示例
<a name="s3-examples"></a>

Amazon Simple Storage Service (Amazon S3) 是提供高度可扩展的云存储的 Web 服务。Amazon S3 提供易于使用的对象存储，具有简单的 Web 服务接口，可用于从 Web 上的任何位置存储和检索任意规模的数据。

的所有示例代码都可以在[此 适用于 PHP 的 AWS SDK 处找到 GitHub](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)。

**Topics**
+ [凭据](#examplecredentials)
+ [创建和使用 Amazon S3 存储桶](s3-examples-creating-buckets.md)
+ [管理 Amazon S3 存储桶访问权限](s3-examples-access-permissions.md)
+ [配置 Amazon S3 存储桶](s3-examples-configuring-a-bucket.md)
+ [Amazon S3 分段上传](s3-multipart-upload.md)
+ [Amazon S3 预签名 URL](s3-presigned-url.md)
+ [创建 S3 预签名 POST](s3-presigned-post.md)
+ [使用 Amazon S3 存储桶作为静态 Web 主机](s3-examples-static-web-host.md)
+ [使用 Amazon S3 存储桶策略](s3-examples-bucket-policies.md)
+ [使用 S3 接入点 ARN](s3-examples-access-point-arn.md)
+ [使用多区域接入点](s3-multi-region-access-points.md)

# 使用 适用于 PHP 的 AWS SDK 版本 3 来创建和使用 Amazon S3 存储桶
<a name="s3-examples-creating-buckets"></a>

以下示例演示如何：
+ 使用 [ListBuckets](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-s3-2006-03-01.html#listbuckets) 返回已经过身份验证的请求发件人所拥有的存储桶列表。
+ 使用 [CreateBucket](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-s3-2006-03-01.html#createbucket) 创建新存储桶。
+ 使用 [PutObject](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-s3-2006-03-01.html#putobject) 向存储桶添加对象。

适用于 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) 中所述。

 **导入**。

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

use Aws\S3\S3Client;
```

## 列出存储桶
<a name="list-buckets"></a>

使用以下代码创建 PHP 文件。首先创建用于指定 AWS 区域和版本的 AWS.S3 客户端服务。然后调用 `listBuckets` 方法，它将以存储桶结构数组的形式返回请求发送者拥有的所有 Amazon S3 存储桶。

 **示例代码** 

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

//Listing all S3 Bucket
$buckets = $s3Client->listBuckets();
foreach ($buckets['Buckets'] as $bucket) {
    echo $bucket['Name'] . "\n";
}
```

## 创建存储桶
<a name="create-a-bucket"></a>

使用以下代码创建 PHP 文件。首先创建用于指定 AWS 区域和版本的 AWS.S3 客户端服务。然后调用 `createBucket` 方法并将数组作为参数。唯一的必需字段是“Bucket”键，它包含了表示要创建的存储桶名称的字符串值。但是，您可以用“CreateBucketConfiguration”字段来指定 AWS 区域。如果成功，此方法将返回存储桶的“Location”。

 **示例代码** 

```
function createBucket($s3Client, $bucketName)
{
    try {
        $result = $s3Client->createBucket([
            'Bucket' => $bucketName,
        ]);
        return 'The bucket\'s location is: ' .
            $result['Location'] . '. ' .
            'The bucket\'s effective URI is: ' .
            $result['@metadata']['effectiveUri'];
    } catch (AwsException $e) {
        return 'Error: ' . $e->getAwsErrorMessage();
    }
}

function createTheBucket()
{
    $s3Client = new S3Client([
        'profile' => 'default',
        'region' => 'us-east-1',
        'version' => '2006-03-01'
    ]);

    echo createBucket($s3Client, 'amzn-s3-demo-bucket');
}

// Uncomment the following line to run this code in an AWS account.
// createTheBucket();
```

## 在存储桶中放置对象
<a name="put-an-object-in-a-bucket"></a>

要向新存储桶中添加文件，请使用以下代码创建一个 PHP 文件。

在命令行执行此文件，然后以字符串形式传入要将文件上传到的存储桶的名称，后跟要上传的文件的完整文件路径。

 **示例代码** 

```
$USAGE = "\n" .
    "To run this example, supply the name of an S3 bucket and a file to\n" .
    "upload to it.\n" .
    "\n" .
    "Ex: php PutObject.php <bucketname> <filename>\n";

if (count($argv) <= 2) {
    echo $USAGE;
    exit();
}

$bucket = $argv[1];
$file_Path = $argv[2];
$key = basename($argv[2]);

try {
    //Create a S3Client
    $s3Client = new S3Client([
        'profile' => 'default',
        'region' => 'us-west-2',
        'version' => '2006-03-01'
    ]);
    $result = $s3Client->putObject([
        'Bucket' => $bucket,
        'Key' => $key,
        'SourceFile' => $file_Path,
    ]);
} catch (S3Exception $e) {
    echo $e->getMessage() . "\n";
}
```

# 使用 适用于 PHP 的 AWS SDK 版本 3 来管理 Amazon S3 存储桶访问权限
<a name="s3-examples-access-permissions"></a>

访问控制列表 (ACL) 是基于资源的访问策略选项之一，可用来管理对存储桶和对象的访问。可以使用 ACL 来向其他 AWS 账户授予基本读/写权限。要了解更多信息，请参阅[使用 ACL 管理访问](https://docs.aws.amazon.com/AmazonS3/latest/dev/S3_ACLs_UsingACLs.html)。

以下示例演示如何：
+ 使用 [GetBucketAcl](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-s3-2006-03-01.html#getbucketacl) 获取存储桶的访问控制策略。
+ 使用 [PutBucketAcl](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-s3-2006-03-01.html#putbucketacl) 通过 ACL 设置存储桶权限。

适用于 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) 中所述。

## 获取和设置访问控制列表策略
<a name="get-and-set-an-access-control-list-policy"></a>

 **导入**。

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

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

 **示例代码** 

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

// Gets the access control policy for a bucket
$bucket = 'amzn-s3-demo-bucket';
try {
    $resp = $s3Client->getBucketAcl([
        'Bucket' => $bucket
    ]);
    echo "Succeed in retrieving bucket ACL as follows: \n";
    var_dump($resp);
} catch (AwsException $e) {
    // output error message if fails
    echo $e->getMessage();
    echo "\n";
}

// Sets the permissions on a bucket using access control lists (ACL).
$params = [
    'ACL' => 'public-read',
    'AccessControlPolicy' => [
        // Information can be retrieved from `getBucketAcl` response
        'Grants' => [
            [
                'Grantee' => [
                    'DisplayName' => '<string>',
                    'EmailAddress' => '<string>',
                    'ID' => '<string>',
                    'Type' => 'CanonicalUser',
                    'URI' => '<string>',
                ],
                'Permission' => 'FULL_CONTROL',
            ],
            // ...
        ],
        'Owner' => [
            'DisplayName' => '<string>',
            'ID' => '<string>',
        ],
    ],
    'Bucket' => $bucket,
];

try {
    $resp = $s3Client->putBucketAcl($params);
    echo "Succeed in setting bucket ACL.\n";
} catch (AwsException $e) {
    // Display error message
    echo $e->getMessage();
    echo "\n";
}
```

# 使用 适用于 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());
}
```

# 在版本 3 中使用 Amazon S3 分段上 适用于 PHP 的 AWS SDK 传
<a name="s3-multipart-upload"></a>

单独的 `PutObject` 操作可上传的对象大小上限为 5 GB。但使用分段上传方法（例如，`CreateMultipartUpload`、`UploadPart`、`CompleteMultipartUpload`、`AbortMultipartUpload`），上传对象的大小范围可以在 5 MB 到 5 TB 之间。

以下示例演示如何：
+ 使用将对象上传到 Amazon S3 [ObjectUploader](https://docs.aws.amazon.com/aws-sdk-php/v3/api/class-Aws.S3.ObjectUploader.html)。
+ 使用[MultipartUploader](https://docs.aws.amazon.com/aws-sdk-php/v3/api/class-Aws.S3.MultipartUploader.html)为 Amazon S3 对象创建分段上传。
+ 使用将对象从一个 Amazon S3 位置复制到另一个位置[ObjectCopier](https://docs.aws.amazon.com/aws-sdk-php/v3/api/class-Aws.S3.ObjectCopier.html)。

的所有示例代码都可以在[此 适用于 PHP 的 AWS SDK 处找到 GitHub](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)。

## 对象上传程序
<a name="object-uploader"></a>

如果您不确定是 `PutObject` 还是 `MultipartUploader` 最适合该任务，请使用 `ObjectUploader`。`ObjectUploader` 是使用 `PutObject` 还是 `MultipartUploader` 将大型文件上传到 Amazon S3，取决于有效载荷大小。

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

use Aws\Exception\MultipartUploadException;
use Aws\S3\MultipartUploader;
use Aws\S3\ObjectUploader;
use Aws\S3\S3Client;
```

 **示例代码** 

```
// Create an S3Client.
$s3Client = new S3Client([
    'profile' => 'default',
    'region' => 'us-east-2',
    'version' => '2006-03-01'
]);

$bucket = 'your-bucket';
$key = 'my-file.zip';

// Use a stream instead of a file path.
$source = fopen('/path/to/large/file.zip', 'rb');

$uploader = new ObjectUploader(
    $s3Client,
    $bucket,
    $key,
    $source
);

do {
    try {
        $result = $uploader->upload();
        if ($result["@metadata"]["statusCode"] == '200') {
            print('<p>File successfully uploaded to ' . $result["ObjectURL"] . '.</p>');
        }
        print($result);
        // If the SDK chooses a multipart upload, try again if there is an exception.
        // Unlike PutObject calls, multipart upload calls are not automatically retried.
    } catch (MultipartUploadException $e) {
        rewind($source);
        $uploader = new MultipartUploader($s3Client, $source, [
            'state' => $e->getState(),
        ]);
    }
} while (!isset($result));

fclose($source);
```

### 配置
<a name="object-uploader-configuration"></a>

`ObjectUploader` 对象构造函数接受以下参数：

**`$client`**  
用于执行转移的 `Aws\ClientInterface` 对象。它应是 `Aws\S3\S3Client` 的实例。

**`$bucket`**  
（`string`，*必需*）对象要上传到的存储桶名称。

**`$key`**  
（`string`，*必需*）上传对象使用的键。

**`$body`**  
（`mixed`，*必需*）要上传的对象数据。可以是 `StreamInterface`、PHP 流资源或要上传的数据字符串。

**`$acl`**  
(`string`) 上传对象设置的访问控制列表 (ACL)。默认情况下对象是私有的。

**`$options`**  
用于分段上传的配置选项的关联数组。以下配置选项有效：    
**`add_content_md5`**  
(`bool`) 设置为 true 可自动计算上传的 MD5 校验和。  
**`mup_threshold`**  
（`int`，*默认*：`int(16777216)`）文件大小的字节数。如果文件大小超过此限制，则使用分段上传。  
**`before_complete`**  
(`callable`) 在 `CompleteMultipartUpload` 操作之前调用的回调。此回调应具有类似 `function (Aws\Command $command) {...}` 的函数签名。有关可以添加到`CommandInterface`对象的参数，请参阅 [CompleteMultipartUpload API 参考](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-s3-2006-03-01.html#completemultipartupload)。  
**`before_initiate`**  
(`callable`) 在 `CreateMultipartUpload` 操作之前调用的回调。此回调应具有类似 `function (Aws\Command $command) {...}` 的函数签名。如果文件大小超过 `mup_threshold` 值，SDK 会调用此回调。有关可以添加到`CommandInterface`对象的参数，请参阅 [CreateMultipartUpload API 参考](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-s3-2006-03-01.html#createmultipartupload)。  
**`before_upload`**  
(`callable`) 在任何 `PutObject` 或 `UploadPart` 操作之前调用的回调。此回调应具有类似 `function (Aws\Command $command) {...}` 的函数签名。如果文件大小小于或等于 `mup_threshold` 值，SDK 会调用此回调。有关您可以应用于`PutObject`请求的参数，请参阅 [PutObject API 参考](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-s3-2006-03-01.html#putobject)。有关适用于`UploadPart`请求的参数，请参阅 [UploadPart API 参考](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-s3-2006-03-01.html#uploadpart)。SDK 会忽略任何不适用于 `CommandInterface` 对象所表示操作的参数。  
**`concurrency`**  
（`int`，*默认*：`int(3)`）在分段上传期间允许的并发 `UploadPart` 操作数量上限。  
**`part_size`**  
（`int`，*默认*：`int(5242880)`）进行分段上传时使用的分段大小（以字节为单位）。此值必须在 5 MB（含）和 5 GB（含）之间。  
**`state`**  
(`Aws\Multipart\UploadState`) 表示分段上传状态的对象，用于重新开始上次上传。如果提供了此选项，将忽略 `$bucket` 和 `$key` 参数以及 `part_size` 选项。  
**`params`**  
一个关联数组，用于为每个子命令提供配置选项。例如：  

```
new ObjectUploader($bucket, $key, $body, $acl, ['params' => ['CacheControl' => <some_value>])
```

## MultipartUploader
<a name="multipartuploader"></a>

分段上传可改善较大对象的上传体验。这种方法支持您将对象分成各自独立的部分，既可以按任何顺序上传，也可并行上传。

我们鼓励 Amazon S3 客户针对大于 100 MB 的对象使用分段上传。

## MultipartUploader 对象
<a name="multipartuploader-object"></a>

开发工具包中包含一个特殊的 `MultipartUploader` 对象，可简化分段上传过程。

 **导入** 

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

use Aws\Exception\MultipartUploadException;
use Aws\S3\MultipartUploader;
use Aws\S3\S3Client;
```

 **示例代码** 

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

// Use multipart upload
$source = '/path/to/large/file.zip';
$uploader = new MultipartUploader($s3Client, $source, [
    'bucket' => 'your-bucket',
    'key' => 'my-file.zip',
]);

try {
    $result = $uploader->upload();
    echo "Upload complete: {$result['ObjectURL']}\n";
} catch (MultipartUploadException $e) {
    echo $e->getMessage() . "\n";
}
```

这个上传工具可根据提供的源和配置创建分段数据的生成器，并尝试上传所有分段。如果某些分段上传失败，上传工具将继续上传后面的分段，直到所有源数据均被读取。然后，上传工具重新尝试上传失败的分段，或引发包含有关无法上传的分段的信息的异常。

## 自定义分段上传
<a name="customizing-a-multipart-upload"></a>

您可以设置 `CreateMultipartUpload`、`UploadPart` 和 `CompleteMultipartUpload` 操作的自定义选项，分段上传工具可通过传递给构造函数的回调执行这些操作。

 **导入** 

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

use Aws\S3\MultipartUploader;
use Aws\S3\S3Client;
```

 **示例代码** 

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

// Customizing a multipart upload
$source = '/path/to/large/file.zip';
$uploader = new MultipartUploader($s3Client, $source, [
    'bucket' => 'your-bucket',
    'key' => 'my-file.zip',
    'before_initiate' => function (Command $command) {
        // $command is a CreateMultipartUpload operation
        $command['CacheControl'] = 'max-age=3600';
    },
    'before_upload' => function (Command $command) {
        // $command is an UploadPart operation
        $command['RequestPayer'] = 'requester';
    },
    'before_complete' => function (Command $command) {
        // $command is a CompleteMultipartUpload operation
        $command['RequestPayer'] = 'requester';
    },
]);
```

### 分段上传之间的手动垃圾回收
<a name="manual-garbage-collection-between-part-uploads"></a>

如果您达到大型上传的内存限制，这可能是由于在达到您的内存限制时开发工具包生成的、但尚未由 [PHP 垃圾回收器](https://www.php.net/manual/en/features.gc.php)收集的循环引用导致的。在操作之间手动调用收集算法可允许在达到该限制之前收集循环。以下示例在每个分段上传之前使用回调来调用收集算法。请注意，调用垃圾回收器会降低性能，最佳用法将取决于您的使用案例和环境。

```
$uploader = new MultipartUploader($client, $source, [
   'bucket' => 'your-bucket',
   'key' => 'your-key',
   'before_upload' => function(\Aws\Command $command) {
      gc_collect_cycles();
   }
]);
```

## 从错误中恢复
<a name="recovering-from-errors"></a>

如果在分段上传过程中发生错误，将引发 `MultipartUploadException`。可通过此异常访问 `UploadState` 对象，其中包含分段上传的进度信息。可使用 `UploadState` 重新开始未完成的上传。

 **导入** 

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

use Aws\Exception\MultipartUploadException;
use Aws\S3\MultipartUploader;
use Aws\S3\S3Client;
```

 **示例代码** 

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

$source = '/path/to/large/file.zip';
$uploader = new MultipartUploader($s3Client, $source, [
    'bucket' => 'your-bucket',
    'key' => 'my-file.zip',
]);

//Recover from errors
do {
    try {
        $result = $uploader->upload();
    } catch (MultipartUploadException $e) {
        $uploader = new MultipartUploader($s3Client, $source, [
            'state' => $e->getState(),
        ]);
    }
} while (!isset($result));

//Abort a multipart upload if failed
try {
    $result = $uploader->upload();
} catch (MultipartUploadException $e) {
    // State contains the "Bucket", "Key", and "UploadId"
    $params = $e->getState()->getId();
    $result = $s3Client->abortMultipartUpload($params);
}
```

若通过 `UploadState` 继续上传，将尝试上传尚未上传的分段。状态对象会跟踪缺少的分段，即使这些分段是不连续的。上传工具会读取或搜寻提供的源文件，找到仍需上传的特定分段的字节范围。

 `UploadState` 对象是序列化的，因此您也可以在另一进程中重新开始上传。即使不是在处理异常，您也可以通过调用 `$uploader->getState()` 获得 `UploadState` 对象。

**重要**  
作为源传递到 `MultipartUploader` 的流在上传之前不会自动倒回。如果您在与上个示例类似的循环中使用流，而不是文件路径，请重置 `catch` 块中的 `$source` 变量。

 **导入** 

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

use Aws\Exception\MultipartUploadException;
use Aws\S3\MultipartUploader;
use Aws\S3\S3Client;
```

 **示例代码** 

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

//Using stream instead of file path
$source = fopen('/path/to/large/file.zip', 'rb');
$uploader = new MultipartUploader($s3Client, $source, [
    'bucket' => 'your-bucket',
    'key' => 'my-file.zip',
]);

do {
    try {
        $result = $uploader->upload();
    } catch (MultipartUploadException $e) {
        rewind($source);
        $uploader = new MultipartUploader($s3Client, $source, [
            'state' => $e->getState(),
        ]);
    }
} while (!isset($result));
fclose($source);
```

### 中止分段上传
<a name="aborting-a-multipart-upload"></a>

通过检索 `UploadState` 对象中包含的 `UploadId` 并将其传递给 `abortMultipartUpload` 可以中止分段上传。

```
try {
    $result = $uploader->upload();
} catch (MultipartUploadException $e) {
    // State contains the "Bucket", "Key", and "UploadId"
    $params = $e->getState()->getId();
    $result = $s3Client->abortMultipartUpload($params);
}
```

## 异步分段上传
<a name="asynchronous-multipart-uploads"></a>

在 `upload()` 上调用 `MultipartUploader` 是一个阻止请求。如果在异步环境中工作，可获得分段上传的 [Promise](guide_promises.md)。

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

use Aws\S3\MultipartUploader;
use Aws\S3\S3Client;
```

 **示例代码** 

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

$source = '/path/to/large/file.zip';
$uploader = new MultipartUploader($s3Client, $source, [
    'bucket' => 'your-bucket',
    'key' => 'my-file.zip',
]);

$promise = $uploader->promise();
```

### 配置
<a name="asynchronous-multipart-uploads-configuration"></a>

`MultipartUploader` 对象构造函数接受以下参数：

** `$client` **  
用于执行转移的 `Aws\ClientInterface` 对象。它应是 `Aws\S3\S3Client` 的实例。

** `$source` **  
上传的源数据。这可以是路径或 URL（例如，`/path/to/file.jpg`）、资源处理（例如，`fopen('/path/to/file.jpg', 'r)`）或 [PSR-7 流](https://docs.aws.amazon.com/aws-sdk-php/v3/api/class-Psr.Http.Message.StreamInterface.html)的实例。

** `$config` **  
用于分段上传的配置选项的关联数组。  
以下配置选项有效：    
** `acl` **  
(`string`) 上传对象设置的访问控制列表 (ACL)。默认情况下对象是私有的。  
** `before_complete` **  
(`callable`) 在 `CompleteMultipartUpload` 操作之前调用的回调。此回调应具有类似 `function (Aws\Command $command) {...}` 的函数签名。  
** `before_initiate` **  
(`callable`) 在 `CreateMultipartUpload` 操作之前调用的回调。此回调应具有类似 `function (Aws\Command $command) {...}` 的函数签名。  
** `before_upload` **  
(`callable`) 在任何 `UploadPart` 操作之前调用的回调。此回调应具有类似 `function (Aws\Command $command) {...}` 的函数签名。  
** `bucket` **  
（`string`，*必需*）对象要上传到的存储桶名称。  
** `concurrency` **  
（`int`，*默认*：`int(5)`）在分段上传期间允许的并发 `UploadPart` 操作数量上限。  
** `key` **  
（`string`，*必需*）上传对象使用的键。  
** `part_size` **  
（`int`，*默认*：`int(5242880)`）进行分段上传时使用的分段大小（以字节为单位）。它必须在 5 MB（含）和 5 GB（含）之间。  
** `state` **  
(`Aws\Multipart\UploadState`) 表示分段上传状态的对象，用于重新开始上次上传。如果提供了此选项，将忽略 `bucket`、`key` 和 `part_size` 选项。  
**`add_content_md5`**  
(`boolean`) 设置为 true 可自动计算上传的 MD5 校验和。  
**`params`**  
一个关联数组，用于为每个子命令提供配置选项。例如：  

```
new MultipartUploader($client, $source, ['params' => ['CacheControl' => <some_value>]])
```

## 分段副本
<a name="multipart-copies"></a>

 适用于 PHP 的 AWS SDK 还包括一个`MultipartCopy`对象，该对象的使用方式与类似`MultipartUploader`，但设计用于在 Amazon S3 中复制大小在 5 GB 到 5 TB 之间的对象。

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

use Aws\Exception\MultipartUploadException;
use Aws\S3\MultipartCopy;
use Aws\S3\S3Client;
```

 **示例代码** 

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

//Copy objects within S3
$copier = new MultipartCopy($s3Client, '/bucket/key?versionId=foo', [
    'bucket' => 'your-bucket',
    'key' => 'my-file.zip',
]);

try {
    $result = $copier->copy();
    echo "Copy complete: {$result['ObjectURL']}\n";
} catch (MultipartUploadException $e) {
    echo $e->getMessage() . "\n";
}
```

# 适用于 PHP 的 AWS SDK 版本 3 的亚马逊 S3 预签名网址
<a name="s3-presigned-url"></a>

您可以通过传递请求信息作为查询字符串参数，而不是使用授权 HTTP 标头来验证特定类型的请求。这在允许第三方浏览器直接访问您的私有 Amazon S3 数据，而无需代理请求时非常有用。其概念是构造一个“预签名”的请求并将其编码为另一个用户可以使用的 URL。此外，您还可以通过指定过期时间来限制预签名请求。

## 为 HTTP GET 请求创建预签名 URL
<a name="s3-presigned-url-get"></a>

以下代码示例演示了如何使用适用于 PHP 的 SDK 为 HTTP GET 请求创建预签名 URL。

```
<?php

require 'vendor/autoload.php';

use Aws\S3\S3Client;

$s3Client = new S3Client([
    'region' => 'us-west-2',
]);

// Supply a CommandInterface object and an expires parameter to the `createPresignedRequest` method.
$request = $s3Client->createPresignedRequest(
    $s3Client->getCommand('GetObject', [
        'Bucket' => 'amzn-s3-demo-bucket',
        'Key' => 'demo-key',
    ]),
    '+1 hour'
);

// From the resulting RequestInterface object, you can get the URL.
$presignedUrl = (string) $request->getUri();

echo $presignedUrl;
```

[`createPresignedRequest` 方法的 API 参考](https://docs.aws.amazon.com/aws-sdk-php/v3/api/class-Aws.S3.S3Client.html#method_createPresignedRequest)提供了更多详细信息。

其他人可以在接下来的一个小时内使用 `$presignedUrl` 值来检索对象。当发出 HTTP GET 请求时（例如使用浏览器），在 S3 服务看来，该调用来自创建了预签名 URL 的用户。

## 为 HTTP PUT 请求创建预签名 URL
<a name="s3-presigned-url-put"></a>

以下代码示例演示了如何使用适用于 PHP 的 SDK 为 HTTP PUT 请求创建预签名 URL。

```
<?php

require 'vendor/autoload.php';

use Aws\S3\S3Client;

$s3Client = new S3Client([
    'region' => 'us-west-2',
]);

$request = $s3Client->createPresignedRequest(
    $s3Client->getCommand('PutObject', [
        'Bucket' => 'amzn-s3-demo-bucket',
        'Key' => 'demo-key',
    ]),
    '+1 hour'
);

// From the resulting RequestInterface object, you can get the URL.
$presignedUrl = (string) $request->getUri();
```

其他人现在可以在 HTTP PUT 请求中使用预签名 URL 来上传文件：

```
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Response;

// ...

function uploadWithPresignedUrl($presignedUrl, $filePath, $s3Client): ?Response
{
    // Get the HTTP handler from the S3 client.
    $handler = $s3Client->getHandlerList()->resolve();
    
    // Create a stream from the file.
    $fileStream = new Stream(fopen($filePath, 'r'));
    
    // Create the request.
    $request = new Request(
        'PUT',
        $presignedUrl,
        [
            'Content-Type' => mime_content_type($filePath),
            'Content-Length' => filesize($filePath)
        ],
        $fileStream
    );
    
    // Send the request using the handler.
    try {
        $promise = $handler($request, []);
        $response = $promise->wait();
        return $response;
    } catch (Exception $e) {
        echo "Error uploading file: " . $e->getMessage() . "\n";
        return null;
    }
}
```

# 使用 适用于 PHP 的 AWS SDK 版本 3 的 Amazon S3 预签名 POST
<a name="s3-presigned-post"></a>

与预签名 URL 极其相似，预签名 POST 使您无需向用户提供 AWS 凭证便可向其授予写入访问权限。可以在 [AwsS3PostObjectV4](https://docs.aws.amazon.com/aws-sdk-php/v3/api/class-Aws.S3.PostObjectV4.html) 实例的帮助下创建预签名 POST 表单。

以下示例演示如何：
+ 使用 [PostObjectV4](https://docs.aws.amazon.com/aws-sdk-php/v3/api/class-Aws.S3.PostObjectV4.html) 获取 S3 Object POST 上传的数据。

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

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

**注意**  
`PostObjectV4` 不能使用来自 AWS IAM Identity Center 的凭证。

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

## 创建 PostObjectV4
<a name="create-postobjectv4"></a>

要创建 `PostObjectV4` 的实例，必须提供以下内容：
+ `Aws\S3\S3Client` 的实例 
+ 桶
+ 表单输入字段的关联数组
+ 一系列策略条件（请参阅 Amazon Simple Storage Service 用户指南中的[策略构建](https://docs.aws.amazon.com/AmazonS3/latest/dev/HTTPPOSTForms.html)）
+ 策略的过期时间字符串（可选，默认为 1 小时）。

 **导入**。

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

use Aws\S3\PostObjectV4;
use Aws\S3\S3Client;
```

 **示例代码** 

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

use Aws\S3\PostObjectV4;
use Aws\S3\S3Client;

$client = new S3Client([
    'profile' => 'default',
    'region' => 'us-east-1',
]);
$bucket = 'amzn-s3-demo-bucket10';
$starts_with = 'user/eric/';
$client->listBuckets();

// Set defaults for form input fields.
$formInputs = ['acl' => 'public-read'];

// Construct an array of conditions for policy.
$options = [
    ['acl' => 'public-read'],
    ['bucket' => $bucket],
    ['starts-with', '$key', $starts_with],
];

// Set an expiration time (optional).
$expires = '+2 hours';

$postObject = new PostObjectV4(
    $client,
    $bucket,
    $formInputs,
    $options,
    $expires
);

// Get attributes for the HTML form, for example, action, method, enctype.
$formAttributes = $postObject->getFormAttributes();

// Get attributes for the HTML form values.
$formInputs = $postObject->getFormInputs();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
    <title>PHP</title>
</head>
<body>
<form action="<?php echo $formAttributes['action'] ?>" method="<?php echo $formAttributes['method'] ?>"
      enctype="<?php echo $formAttributes['enctype'] ?>">
    <label id="key">
        <input hidden type="text" name="key" value="<?php echo $starts_with ?><?php echo $formInputs['key'] ?>"/>
    </label>
    <h3>$formInputs:</h3>
    acl: <label id="acl">
        <input readonly type="text" name="acl" value="<?php echo $formInputs['acl'] ?>"/>
    </label><br/>
    X-Amz-Credential: <label id="credential">
        <input readonly type="text" name="X-Amz-Credential" value="<?php echo $formInputs['X-Amz-Credential'] ?>"/>
    </label><br/>
    X-Amz-Algorithm: <label id="algorithm">
        <input readonly type="text" name="X-Amz-Algorithm" value="<?php echo $formInputs['X-Amz-Algorithm'] ?>"/>
    </label><br/>
    X-Amz-Date: <label id="date">
        <input readonly type="text" name="X-Amz-Date" value="<?php echo $formInputs['X-Amz-Date'] ?>"/>
    </label><br/><br/><br/>
    Policy: <label id="policy">
        <input readonly type="text" name="Policy" value="<?php echo $formInputs['Policy'] ?>"/>
    </label><br/>
    X-Amz-Signature: <label id="signature">
        <input readonly type="text" name="X-Amz-Signature" value="<?php echo $formInputs['X-Amz-Signature'] ?>"/>
    </label><br/><br/>
    <h3>Choose file:</h3>
    <input type="file" name="file"/> <br/><br/>
    <h3>Upload file:</h3>
    <input type="submit" name="submit" value="Upload to Amazon S3"/>
</form>
</body>
</html>
```

# 使用 Amazon S3 存储桶作为具有 适用于 PHP 的 AWS SDK 版本 3 的静态 Web 主机
<a name="s3-examples-static-web-host"></a>

您可以在 Amazon S3 上托管静态网站。要了解更多信息，请参阅[在 Amazon S3 上托管静态网站](https://docs.aws.amazon.com/AmazonS3/latest/dev/WebsiteHosting.html)。

以下示例演示如何：
+ 使用 [GetBucketWebsite](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-s3-2006-03-01.html#getbucketwebsite) 获取存储桶的网站配置。
+ 使用 [PutBucketWebsite](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-s3-2006-03-01.html#putbucketwebsite) 设置存储桶的网站配置。
+ 使用 [DeleteBucketWebsite](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-s3-2006-03-01.html#deletebucketwebsite) 从存储桶中删除网站配置。

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

## 凭证
<a name="credentials-s3-examples-static-web-host"></a>

运行示例代码之前，请配置您的 AWS 凭证。请参阅 [适用于 PHP 的 AWS SDK 版本 3 的凭证](guide_credentials.md)。

## 获取、设置和删除存储桶的网站配置。
<a name="get-set-and-delete-the-website-configuration-for-a-bucket"></a>

 **导入**。

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

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

 **示例代码** 

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

// Retrieving the Bucket Website Configuration
$bucket = 'amzn-s3-demo-bucket';
try {
    $resp = $s3Client->getBucketWebsite([
        'Bucket' => $bucket
    ]);
    echo "Succeed in retrieving website configuration for bucket: " . $bucket . "\n";
} catch (AwsException $e) {
    // output error message if fails
    echo $e->getMessage();
    echo "\n";
}

// Setting a Bucket Website Configuration
$params = [
    'Bucket' => $bucket,
    'WebsiteConfiguration' => [
        'ErrorDocument' => [
            'Key' => 'foo',
        ],
        'IndexDocument' => [
            'Suffix' => 'bar',
        ],
    ]
];

try {
    $resp = $s3Client->putBucketWebsite($params);
    echo "Succeed in setting bucket website configuration.\n";
} catch (AwsException $e) {
    // Display error message
    echo $e->getMessage();
    echo "\n";
}

// Deleting a Bucket Website Configuration
try {
    $resp = $s3Client->deleteBucketWebsite([
        'Bucket' => $bucket
    ]);
    echo "Succeed in deleting policy for bucket: " . $bucket . "\n";
} catch (AwsException $e) {
    // output error message if fails
    echo $e->getMessage();
    echo "\n";
}
```

# 结合使用 Amazon S3 存储桶策略与 适用于 PHP 的 AWS SDK 版本 3
<a name="s3-examples-bucket-policies"></a>

您可以使用存储桶策略来授予对 Amazon S3 资源的权限。有关更多信息，请参阅[使用存储桶策略和用户策略](https://docs.aws.amazon.com/AmazonS3/latest/dev/using-iam-policies.html)。

以下示例演示如何：
+ 使用 [GetBucketPolicy](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-s3-2006-03-01.html#getbucketpolicy) 返回用于指定存储桶的策略。
+ 使用 [PutBucketPolicy](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-s3-2006-03-01.html#putbucketpolicy) 替换存储桶策略。
+ 使用 [DeleteBucketPolicy](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-s3-2006-03-01.html#deletebucketpolicy) 从存储桶中删除策略。

适用于 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) 中所述。

## 获取、删除和替换存储桶策略
<a name="get-delete-and-replace-a-policy-on-a-bucket"></a>

 **导入**。

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

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

 **示例代码** 

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

$bucket = 'amzn-s3-demo-bucket';

// Get the policy of a specific bucket
try {
    $resp = $s3Client->getBucketPolicy([
        'Bucket' => $bucket
    ]);
    echo "Succeed in receiving bucket policy:\n";
    echo $resp->get('Policy');
    echo "\n";
} catch (AwsException $e) {
    // Display error message
    echo $e->getMessage();
    echo "\n";
}

// Deletes the policy from the bucket
try {
    $resp = $s3Client->deleteBucketPolicy([
        'Bucket' => $bucket
    ]);
    echo "Succeed in deleting policy of bucket: " . $bucket . "\n";
} catch (AwsException $e) {
    // Display error message
    echo $e->getMessage();
    echo "\n";
}

// Replaces a policy on the bucket
try {
    $resp = $s3Client->putBucketPolicy([
        'Bucket' => $bucket,
        'Policy' => 'foo policy',
    ]);
    echo "Succeed in put a policy on bucket: " . $bucket . "\n";
} catch (AwsException $e) {
    // Display error message
    echo $e->getMessage();
    echo "\n";
}
```

# 结合使用 S3 接入点 ARN 与 适用于 PHP 的 AWS SDK 版本 3
<a name="s3-examples-access-point-arn"></a>

S3 引入了接入点，这是与 S3 存储桶交互的一种新方式。接入点上可以应用唯一的策略和配置，而不是直接应用到存储桶。通过 适用于 PHP 的 AWS SDK，您可以在存储桶字段中使用接入点 ARN 进行 API 操作，而不是明确指定存储桶名称。有关 S3 接入点和 ARN 工作原理的更多详细信息，可在[此处](https://docs.aws.amazon.com/AmazonS3/latest/dev/using-access-points.html)找到。以下示例演示如何：
+ 将 [GetObject](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-s3-2006-03-01.html#getobject) 与接入点 ARN 一起使用，从存储桶中提取对象。
+ 将 [PutoBject](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-s3-2006-03-01.html#putobject) 与接入点 ARN 一起使用，将对象添加到存储桶中。
+ 将 S3 客户端配置为使用 ARN 区域而不是客户端区域。

适用于 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) 中所述。

 **导入**。

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

use Aws\S3\S3Client;
```

## 获取对象
<a name="get-object"></a>

首先创建用于指定 AWS 区域和版本的 AWS.S3 客户端服务。然后 `getObject` 使用您的密钥并在 `Bucket` 字段中使用 S3 接入点 ARN 调用该方法，以从与该接入点关联的存储桶中获取对象。

 **示例代码** 

```
$s3 = new S3Client([
    'version'     => 'latest',
    'region'      => 'us-west-2',
]);
$result = $s3->getObject([
    'Bucket' => 'arn:aws:s3:us-west-2:123456789012:accesspoint:endpoint-name',
    'Key' => 'MyKey'
]);
```

## 在存储桶中放置对象
<a name="put-an-object-in-a-bucket"></a>

首先创建用于指定 AWS 区域和版本的 AWS.S3 客户端服务。然后使用所需的密钥、正文或源文件并在 `putObject` 字段中使用 S3 接入点 ARN 调用 `Bucket` 方法，这会将对象放入与该接入点关联的存储桶中。

 **示例代码** 

```
$s3 = new S3Client([
    'version'     => 'latest',
    'region'      => 'us-west-2',
]);
$result = $s3->putObject([
    'Bucket' => 'arn:aws:s3:us-west-2:123456789012:accesspoint:endpoint-name',
    'Key' => 'MyKey',
    'Body' => 'MyBody'
]);
```

## 将 S3 客户端配置为使用 ARN 区域而不是客户端区域
<a name="configure-the-s3-client-to-use-the-arn-region-instead-of-the-client-region"></a>

在 S3 客户端操作中使用 S3 接入点 ARN 时，默认情况下，客户端将确保 ARN 区域与客户端区域匹配，如果不匹配则引发异常。通过将 `use_arn_region` 配置选项设置为 `true`，可将此行为更改为接受 ARN 区域而不是客户端区域。默认情况下，该选项设置为 `false`。

 **示例代码** 

```
$s3 = new S3Client([
    'version'        => 'latest',
    'region'         => 'us-west-2',
    'use_arn_region' => true
]);
```

客户端还将按以下优先顺序检查环境变量和配置文件选项：

1. 客户端选项 `use_arn_region`，如上例所示。

1. 环境变量 `AWS_S3_USE_ARN_REGION` 

```
export AWS_S3_USE_ARN_REGION=true
```

1. AWS 共享配置文件（默认情况下位于 `~/.aws/config` 中）中的配置变量 `s3_use_arn_region`。

```
[default]
s3_use_arn_region = true
```

# 将 Amazon S3 多区域接入点与 适用于 PHP 的 AWS SDK 版本 3 配合使用
<a name="s3-multi-region-access-points"></a>

[Amazon Simple Storage Service（S3）多区域接入点](https://docs.aws.amazon.com//AmazonS3/latest/userguide/MultiRegionAccessPoints.html)提供了一个全局端点，用于在 AWS 区域之间路由 Amazon S3 请求流量。

您可以使用适用于 [PHP 的 SDK、另一个 AWS SDK、S3 控制台或 AWS CLI 来](https://docs.aws.amazon.com//aws-sdk-php/v3/api/api-s3control-2018-08-20.html#createmultiregionaccesspoint)[创建多区域接入点，](https://docs.aws.amazon.com//AmazonS3/latest/userguide/multi-region-access-point-create-examples.html)

**重要**  
要将多区域接入点与适用于 PHP 的 SDK 配合使用，您的 PHP 环境必须安装[AWS 通用运行时 (AWS CRT) 扩展](guide_crt.md)。

当创建多区域接入点时，Amazon S3 会生成一个具有以下格式的 Amazon 资源名称（ARN）：

`arn:aws:s3::account-id:accesspoint/MultiRegionAccessPoint_alias`

您可以使用生成的 ARN 来代替 `[getObject()](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-s3-2006-03-01.html#getobject)` 和 `[putObject()](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-s3-2006-03-01.html#putobject)` 方法的存储桶名称。

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

use Aws\S3\S3Client;

// Assign the Multi-Region Access Point to a variable and use it place of a bucket name.
$mrap = 'arn:aws:s3::123456789012:accesspoint/mfzwi23gnjvgw.mrap';
$key = 'my-key';

$s3Client = new S3Client([
    'region' => 'us-east-1'
]);

$s3Client->putObject([
    'Bucket' => $mrap,
    'Key' => $key,
    'Body' => 'Hello World!'
]);

$result = $s3Client->getObject([
    'Bucket' => $mrap,
    'Key' => $key
]);

echo $result['Body'] . "\n";

// Clean up.
$result = $s3Client->deleteObject([
    'Bucket' => $mrap,
    'Key' => $key
]);

$s3Client->waitUntil('ObjectNotExists', ['Bucket' => $mrap, 'Key' => $key]);

echo "Object deleted\n";
```

# 使用 Secrets Manager API 和 适用于 PHP 的 AWS SDK 版本 3 来管理密钥
<a name="secretsmanager-examples-manage-secret"></a>

AWS Secrets Manager 存储和管理共享密钥，如密码、API 密钥和数据库凭证。借助 Secrets Manager 服务，开发人员可以将已部署代码中的硬编码的凭证替换为对 Secrets Manager 的嵌入式调用。

Secrets Manager 原生支持对 Amazon Relational Database Service (Amazon RDS) 数据库的自动计划凭证轮换，从而增强应用程序安全性。Secrets Manager 还可以使用 AWS Lambda 来无缝轮换其他数据库和第三方服务的密钥，以实现特定于服务的详细信息。

以下示例演示如何：
+ 使用 [CreateSecret](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-secretsmanager-2017-10-17.html#createsecret) 创建密钥。
+ 使用 [GetSecretValue](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-secretsmanager-2017-10-17.html#getsecretvalue) 检索密钥。
+ 使用 [ListSecrets](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-secretsmanager-2017-10-17.html#listsecrets) 列出 Secrets Manager 存储的所有密钥。
+ 使用 [DescribeSecret](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-secretsmanager-2017-10-17.html#describesecret) 获取有关指定密钥的详细信息。
+ 使用 [PutSecretValue](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-secretsmanager-2017-10-17.html#putsecretvalue) 更新指定密钥。
+ 使用 [RotateSecret](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-secretsmanager-2017-10-17.html#rotatesecret) 设置密钥轮换。
+ 使用 [DeleteSecret](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-secretsmanager-2017-10-17.html#deletesecret) 标记密钥以进行删除。

适用于 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) 中所述。

## 在 Secrets Manager 中创建密钥
<a name="create-a-secret-in-asm"></a>

要在 Secrets Manager 中创建密钥，请使用 [CreateSecret](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-secretsmanager-2017-10-17.html#createsecret) 操作。

在此示例中，用户名和密码将存储为 JSON 字符串。

 **导入**。

```
require 'vendor/autoload.php';
use Aws\SecretsManager\SecretsManagerClient;
use Aws\Exception\AwsException;
```

 **示例代码** 

```
$client = new SecretsManagerClient([
    'profile' => 'default',
    'version' => '2017-10-17',
    'region' => 'us-west-2'
]);
$secretName = 'MySecretName';
$secret = json_encode([
    "username" => getenv("SMDEMO_USERNAME"),
    "password" => getenv("SMDEMO_PASSWORD"),
]);
$description = '<<Description>>';
try {
    $result = $client->createSecret([
        'Description' => $description,
        'Name' => $secretName,
        'SecretString' => $secret,
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    echo $e->getMessage();
    echo "\n";
}
```

## 从 Secrets Manager 中检索密钥
<a name="retrieve-a-secret-from-asm"></a>

要检索存储在 Secrets Manager 中的密钥值，请使用 [GetSecretValue](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-secretsmanager-2017-10-17.html#getsecretvalue) 操作。

在此示例中，`secret` 是一个包含存储值的字符串。如果 `username` 的值为 `<<USERNAME>>`，并且 `password` 的值为 `<<PASSWORD>>`，则 `secret` 的输出为：

```
{"username":"<<USERNAME>>","password":"<<PASSWORD>>"}
```

用 `json_decode($secret, true)` 来访问数组值。

 **导入**。

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

use Aws\SecretsManager\SecretsManagerClient;
use Aws\Exception\AwsException;
```

 **示例代码** 

```
$client = new SecretsManagerClient([
    'profile' => 'default',
    'version' => '2017-10-17',
    'region' => 'us-east-1',
]);

$secretName = 'MySecretName';

try {
    $result = $client->getSecretValue([
        'SecretId' => $secretName,
    ]);
} catch (AwsException $e) {
    $error = $e->getAwsErrorCode();
    if ($error == 'DecryptionFailureException') {
        // Secrets Manager can't decrypt the protected secret text using the provided AWS KMS key.
        // Handle the exception here, and/or rethrow as needed.
        throw $e;
    }
    if ($error == 'InternalServiceErrorException') {
        // An error occurred on the server side.
        // Handle the exception here, and/or rethrow as needed.
        throw $e;
    }
    if ($error == 'InvalidParameterException') {
        // You provided an invalid value for a parameter.
        // Handle the exception here, and/or rethrow as needed.
        throw $e;
    }
    if ($error == 'InvalidRequestException') {
        // You provided a parameter value that is not valid for the current state of the resource.
        // Handle the exception here, and/or rethrow as needed.
        throw $e;
    }
    if ($error == 'ResourceNotFoundException') {
        // We can't find the resource that you asked for.
        // Handle the exception here, and/or rethrow as needed.
        throw $e;
    }
}
// Decrypts secret using the associated KMS CMK.
// Depending on whether the secret is a string or binary, one of these fields will be populated.
if (isset($result['SecretString'])) {
    $secret = $result['SecretString'];
} else {
    $secret = base64_decode($result['SecretBinary']);
}
print $secret;
$secretArray = json_decode($secret, true);
$username = $secretArray['username'];
$password = $secretArray['password'];

// Your code goes here;
```

## 列出 Secrets Manager 中存储的密钥
<a name="list-secrets-stored-in-asm"></a>

使用 [ListSecrets](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-secretsmanager-2017-10-17.html#listsecrets) 操作获取由 Secrets Manager 存储的所有密钥的列表。

 **导入**。

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

use Aws\SecretsManager\SecretsManagerClient;
use Aws\Exception\AwsException;
```

 **示例代码** 

```
$client = new SecretsManagerClient([
    'profile' => 'default',
    'version' => '2017-10-17',
    'region' => 'us-west-2'
]);

try {
    $result = $client->listSecrets([
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    echo $e->getMessage();
    echo "\n";
}
```

## 检索有关密钥的详细信息
<a name="retrieve-details-about-a-secret"></a>

存储的密钥包含有关轮换规则、上次访问或更改密钥、用户创建的标签和 Amazon 资源名称 (ARN) 的元数据。要获取存储在 Secrets Manager 中的指定密钥的详细信息，请使用 [DescribeSecret](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-secretsmanager-2017-10-17.html#describesecret) 操作。

 **导入**。

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

use Aws\SecretsManager\SecretsManagerClient;
use Aws\Exception\AwsException;
```

 **示例代码** 

```
$client = new SecretsManagerClient([
    'profile' => 'default',
    'version' => '2017-10-17',
    'region' => 'us-west-2'
]);

$secretName = 'MySecretName';

try {
    $result = $client->describeSecret([
        'SecretId' => $secretName,
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    echo $e->getMessage();
    echo "\n";
}
```

## 更新密钥值
<a name="update-the-secret-value"></a>

要将新加密的密钥值存储在 Secrets Manager 中，请使用 [PutSecretValue](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-secretsmanager-2017-10-17.html#putsecretvalue) 操作。

这将创建密钥的一个新版本。如果密钥的某个版本已存在，则在 `VersionStages` 中添加带该值的 `AWSCURRENT` 参数，以确保在检索该值时使用新值。

 **导入**。

```
require 'vendor/autoload.php';
use Aws\SecretsManager\SecretsManagerClient;
use Aws\Exception\AwsException;
```

 **示例代码** 

```
$client = new SecretsManagerClient([
    'profile' => 'default',
    'version' => '2017-10-17',
    'region' => 'us-west-2'
]);
$secretName = 'MySecretName';
$secret = json_encode([
    "username" => getenv("SMDEMO_USERNAME"),
    "password" => getenv("SMDEMO_PASSWORD"),
]);
try {
    $result = $client->putSecretValue([
        'SecretId' => $secretName,
        'SecretString' => $secret,
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    echo $e->getMessage();
    echo "\n";
}
```

## 将值轮换到 Secrets Manager 中的现有密钥
<a name="rotate-the-value-to-an-existing-secret-in-asm"></a>

要轮换存储在 Secrets Manager 中的现有密钥的值，请使用 Lambda 轮换函数和 [RotateSecret](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-secretsmanager-2017-10-17.html#rotatesecret) 操作。

在开始之前，请创建一个 Lambda 函数来轮换您的密钥。[AWS 代码示例目录](https://docs.aws.amazon.com/code-samples/latest/catalog/code-catalog-lambda_functions-secretsmanager.html)目前包含用于轮换 Amazon RDS 数据库凭证的多个 Lambda 代码示例。

**注意**  
有关轮换密钥的更多信息，请参阅 AWS Secrets Manager 用户指南中的[轮换 AWS Secrets Manager 密钥](https://docs.aws.amazon.com/secretsmanager/latest/userguide/rotating-secrets.html)。

设置您的 Lambda 函数后，配置一个新的密钥轮换。

 **导入**。

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

use Aws\SecretsManager\SecretsManagerClient;
use Aws\Exception\AwsException;
```

 **示例代码** 

```
$client = new SecretsManagerClient([
    'profile' => 'default',
    'version' => '2017-10-17',
    'region' => 'us-west-2'
]);

$secretName = 'MySecretName';
$lambda_ARN = 'arn:aws:lambda:us-west-2:123456789012:function:MyTestDatabaseRotationLambda';
$rules = ['AutomaticallyAfterDays' => 30];

try {
    $result = $client->rotateSecret([
        'RotationLambdaARN' => $lambda_ARN,
        'RotationRules' => $rules,
        'SecretId' => $secretName,
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    echo $e->getMessage();
    echo "\n";
}
```

配置轮换时，您可以使用 [RotateSecret](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-secretsmanager-2017-10-17.html#rotatesecret) 操作实施轮换。

 **导入**。

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

use Aws\SecretsManager\SecretsManagerClient;
use Aws\Exception\AwsException;
```

 **示例代码** 

```
$client = new SecretsManagerClient([
    'profile' => 'default',
    'version' => '2017-10-17',
    'region' => 'us-west-2'
]);

$secretName = 'MySecretName';

try {
    $result = $client->rotateSecret([
        'SecretId' => $secretName,
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    echo $e->getMessage();
    echo "\n";
}
```

## 从 Secrets Manager 中删除密钥
<a name="delete-a-secret-from-asm"></a>

要从 Secrets Manager 中删除指定密钥，请使用 [DeleteSecret](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-secretsmanager-2017-10-17.html#deletesecret) 操作。要防止意外删除密钥，将自动为密钥添加 DeletionDate 戳，用于指定您可恢复删除的恢复时间范围。如果未指定恢复时间窗口的范围，则默认时间范围为 30 天。

 **导入**。

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

use Aws\SecretsManager\SecretsManagerClient;
use Aws\Exception\AwsException;
```

 **示例代码** 

```
$client = new SecretsManagerClient([
    'profile' => 'default',
    'version' => '2017-10-17',
    'region' => 'us-west-2'
]);

$secretName = 'MySecretName';

try {
    $result = $client->deleteSecret([
        'SecretId' => $secretName,
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    echo $e->getMessage();
    echo "\n";
}
```

## 相关信息
<a name="related-information"></a>

适用于 PHP 的 AWS SDK 示例使用 AWS Secrets Manager API 参考中的以下 REST 操作：
+  [CreateSecret](https://docs.aws.amazon.com/secretsmanager/latest/apireference/API_CreateSecret.html) 
+  [GetSecretValue](https://docs.aws.amazon.com/secretsmanager/latest/apireference/API_GetSecretValue.html) 
+  [ListSecrets](https://docs.aws.amazon.com/secretsmanager/latest/apireference/API_ListSecrets.html) 
+  [DescribeSecret](https://docs.aws.amazon.com/secretsmanager/latest/apireference/API_DescribeSecret.html) 
+  [PutSecretValue](https://docs.aws.amazon.com/secretsmanager/latest/apireference/API_PutSecretValue.html) 
+  [： RotateSecret](https://docs.aws.amazon.com/secretsmanager/latest/apireference/API_RotateSecret.html) 
+  [DeleteSecret](https://docs.aws.amazon.com/secretsmanager/latest/apireference/API_DeleteSecret.html) 

有关使用 AWS Secrets Manager 的更多信息，请参阅 [AWS Secrets Manager 用户指南](https://docs.aws.amazon.com/secretsmanager/latest/userguide/)。

# 使用 适用于 PHP 的 AWS SDK 版本 3 的 Amazon SES 示例
<a name="ses-examples"></a>

Amazon Simple Email Service (Amazon SES) 是一个易于使用且经济的电子邮件平台，便于您通过该平台，使用您自己的电子邮件地址和域来发送或接收电子邮件。有关 Amazon SES 的更多信息，请参阅 [Amazon SES 开发人员指南](https://docs.aws.amazon.com/ses/latest/DeveloperGuide/)。

AWS 提供了两个 Amazon SES 服务版本，相应地，适用于 PHP 的 SDK 提供了两个客户端版本：[SesClient](https://docs.aws.amazon.com/aws-sdk-php/v3/api/class-Aws.Ses.SesClient.html) 和 [SesV2Client](https://docs.aws.amazon.com/aws-sdk-php/v3/api/class-Aws.SesV2.SesV2Client.html)。尽管方法调用方式或结果可能有所不同，但在很多情况下，客户端的功能是重叠的。这两个 API 还提供专有功能，因此您可以使用两个客户端来访问所有功能。

本部分中的示例都使用原始 `SesClient`。

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

**Topics**
+ [验证电子邮件地址](ses-verify.md)
+ [使用电子邮件模板](ses-template.md)
+ [管理电子邮件筛选条件](ses-filters.md)
+ [使用电子邮件规则](ses-rules.md)
+ [监控发送活动](ses-send-email.md)
+ [向发件人授权](ses-sender-policy.md)

# 使用 Amazon SES API 和 适用于 PHP 的 AWS SDK 版本 3 来验证电子邮件身份
<a name="ses-verify"></a>

当您首次开始使用 Amazon Simple Email Service (Amazon SES) 账户时，您将发送电子邮件到的同一个 AWS 区域中的所有发件人和收件人均必须经过验证。有关发送电子邮件的更多信息，请参阅[使用 Amazon SES 发送电子邮件](https://docs.aws.amazon.com/ses/latest/DeveloperGuide/sending-email.html)。

以下示例演示如何：
+ 使用 [VerifyEmailIdentity](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-email-2010-12-01.html#verifyemailidentity) 验证电子邮件地址。
+ 使用 [VerifyDomainIdentity](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-email-2010-12-01.html#verifydomainidentity) 验证电子邮件域。
+ 使用 [ListIdentities](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-email-2010-12-01.html#listidentities) 列出所有电子邮件地址。
+ 使用 [ListIdentities](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-email-2010-12-01.html#listidentities) 列出所有电子邮件域。
+ 使用 [DeleteIdentity](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-email-2010-12-01.html#deleteidentity) 删除电子邮件地址。
+ 使用 [DeleteIdentity](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-email-2010-12-01.html#deleteidentity) 删除电子邮件域。

适用于 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) 中所述。

有关使用 Amazon SES 的更多信息，请参阅 [Amazon SES 开发人员指南](https://docs.aws.amazon.com/ses/latest/DeveloperGuide/)。

## 验证电子邮件地址
<a name="verifying-email-addresses"></a>

Amazon SES 只能从已验证的电子邮件地址或域发送电子邮件。通过验证电子邮件地址，您可证明您是该地址的所有者，并希望允许 Amazon SES 从该地址发送电子邮件。

运行以下代码示例时，Amazon SES 将向您指定的地址发送一封电子邮件。当您（或电子邮件的收件人）单击电子邮件中的链接时，该地址将得到验证。

要将电子邮件地址添加到您的 Amazon SES 账户，请使用 [VerifyEmailIdentity](https://docs.aws.amazon.com/ses/latest/APIReference/API_VerifyEmailIdentity.html) 操作。

 **导入**。

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

use Aws\Exception\AwsException;
```

 **示例代码** 

```
$SesClient = new Aws\Ses\SesClient([
    'profile' => 'default',
    'version' => '2010-12-01',
    'region' => 'us-east-2'
]);

$email = 'email_address';

try {
    $result = $SesClient->verifyEmailIdentity([
        'EmailAddress' => $email,
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    echo $e->getMessage();
    echo "\n";
}
```

## 验证电子邮件域
<a name="verify-an-email-domain"></a>

Amazon SES 只能从已验证的电子邮件地址或域发送电子邮件。通过验证域，您可证明自己是该域的所有者。在验证域时，允许 Amazon SES 从该域上的任何地址发送电子邮件。

当运行以下代码示例时，Amazon SES 向您提供验证令牌。您必须将令牌添加到域的 DNS 配置。有关更多信息，请参阅 Amazon Simple Email Service 开发人员指南中的[使用 Amazon SES 来验证域](https://docs.aws.amazon.com/ses/latest/DeveloperGuide/verify-domain-procedure.html)。

要将发送域添加到您的 Amazon SES 账户，请使用 [VerifyDomainIdentity](https://docs.aws.amazon.com/ses/latest/APIReference/API_VerifyDomainIdentity.html) 操作。

 **导入**。

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

use Aws\Exception\AwsException;
```

 **示例代码** 

```
$SesClient = new Aws\Ses\SesClient([
    'profile' => 'default',
    'version' => '2010-12-01',
    'region' => 'us-east-2'
]);

$domain = 'domain.name';

try {
    $result = $SesClient->verifyDomainIdentity([
        'Domain' => $domain,
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    echo $e->getMessage();
    echo "\n";
}
```

## 列出电子邮件地址
<a name="list-email-addresses"></a>

要检索在当前 AWS 区域中提交的电子邮件地址的列表，不论验证状态如何，请使用 [ListIdentities](https://docs.aws.amazon.com/ses/latest/APIReference/API_ListIdentities.html) 操作。

 **导入**。

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

use Aws\Exception\AwsException;
```

 **示例代码** 

```
$SesClient = new Aws\Ses\SesClient([
    'profile' => 'default',
    'version' => '2010-12-01',
    'region' => 'us-east-2'
]);

try {
    $result = $SesClient->listIdentities([
        'IdentityType' => 'EmailAddress',
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    echo $e->getMessage();
    echo "\n";
}
```

## 列出电子邮件域
<a name="list-email-domains"></a>

要检索在当前 AWS 区域中提交的电子邮件域的列表，不论验证状态如何，请使用 [ListIdentities](https://docs.aws.amazon.com/ses/latest/APIReference/API_ListIdentities.html) 操作。

 **导入**。

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

use Aws\Exception\AwsException;
```

 **示例代码** 

```
$SesClient = new Aws\Ses\SesClient([
    'profile' => 'default',
    'version' => '2010-12-01',
    'region' => 'us-east-2'
]);

try {
    $result = $SesClient->listIdentities([
        'IdentityType' => 'Domain',
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    echo $e->getMessage();
    echo "\n";
}
```

## 删除电子邮件地址
<a name="delete-an-email-address"></a>

要从身份列表中删除某个经过验证的电子邮件地址，请使用 [DeleteIdentity](https://docs.aws.amazon.com/ses/latest/APIReference/API_DeleteIdentity.html) 操作。

 **导入**。

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

use Aws\Exception\AwsException;
```

 **示例代码** 

```
$SesClient = new Aws\Ses\SesClient([
    'profile' => 'default',
    'version' => '2010-12-01',
    'region' => 'us-east-2'
]);

$email = 'email_address';

try {
    $result = $SesClient->deleteIdentity([
        'Identity' => $email,
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    echo $e->getMessage();
    echo "\n";
}
```

## 删除电子邮件域
<a name="delete-an-email-domain"></a>

要从经过验证的身份列表中删除某个经过验证的电子邮件地址，请使用 [DeleteIdentity](https://docs.aws.amazon.com/ses/latest/APIReference/API_DeleteIdentity.html) 操作。

 **导入**。

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

use Aws\Exception\AwsException;
```

 **示例代码** 

```
$SesClient = new Aws\Ses\SesClient([
    'profile' => 'default',
    'version' => '2010-12-01',
    'region' => 'us-east-2'
]);

$domain = 'domain.name';

try {
    $result = $SesClient->deleteIdentity([
        'Identity' => $domain,
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    echo $e->getMessage();
    echo "\n";
}
```

# 使用 Amazon SES API 和 适用于 PHP 的 AWS SDK 版本 3 来创建自定义电子邮件模板
<a name="ses-template"></a>

Amazon Simple Email Service (Amazon SES) 让您可以通过使用模板，向各个收件人发送个性化的电子邮件。模板包含一个主题行以及电子邮件正文的文本和 HTML 部分。主题和正文部分还可包含针对每个收件人进行个性化设置的唯一值。

有关更多信息，请参阅 Amazon Simple Email Service 开发人员指南中的[使用 Amazon SES 来发送个性化电子邮件](https://docs.aws.amazon.com/ses/latest/DeveloperGuide/send-personalized-email-api.html)。

以下示例演示如何：
+ 使用 [CreateTemplate](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-email-2010-12-01.html#createtemplate) 创建电子邮件模板。
+ 使用 [ListTemplates](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-email-2010-12-01.html#listtemplates) 列出所有电子邮件模板。
+ 使用 [CreateTemplate](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-email-2010-12-01.html#gettemplate) 检索电子邮件模板。
+ 使用 [UpdateTemplate](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-email-2010-12-01.html#updateTemplate) 更新电子邮件模板。
+ 使用 [DeleteTemplate](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-email-2010-12-01.html#deletetemplate) 删除电子邮件模板。
+ 使用 [SendTemplatedEmail](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-email-2010-12-01.html#sendtemplatedemail) 发送模板化电子邮件。

适用于 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) 中所述。

有关使用 Amazon SES 的更多信息，请参阅 [Amazon SES 开发人员指南](https://docs.aws.amazon.com/ses/latest/DeveloperGuide/)。

## 创建电子邮件模板
<a name="create-an-email-template"></a>

要创建模板以发送个性化电子邮件，请使用 [CreateTemplate](https://docs.aws.amazon.com/ses/latest/APIReference/API_CreateTemplate.html) 操作。在添加模板到的 AWS 区域中，模板可由授权发送消息的任意账户使用。

**注意**  
Amazon SES 不会验证您的 HTML，因此请先确认 *HtmlPart* 有效，然后再发送电子邮件。

 **导入**。

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

use Aws\Exception\AwsException;
```

 **示例代码** 

```
$SesClient = new Aws\Ses\SesClient([
    'profile' => 'default',
    'version' => '2010-12-01',
    'region' => 'us-east-2'
]);

$name = 'Template_Name';
$html_body = '<h1>AWS Amazon Simple Email Service Test Email</h1>' .
    '<p>This email was sent with <a href="https://aws.amazon.com/ses/">' .
    'Amazon SES</a> using the <a href="https://aws.amazon.com/sdk-for-php/">' .
    'AWS SDK for PHP</a>.</p>';
$subject = 'Amazon SES test (AWS SDK for PHP)';
$plaintext_body = 'This email was send with Amazon SES using the AWS SDK for PHP.';

try {
    $result = $SesClient->createTemplate([
        'Template' => [
            'HtmlPart' => $html_body,
            'SubjectPart' => $subject,
            'TemplateName' => $name,
            'TextPart' => $plaintext_body,
        ],
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    echo $e->getMessage();
    echo "\n";
}
```

## 获取电子邮件模板
<a name="get-an-email-template"></a>

要查看现有电子邮件模板（包括主题行、HTML 正文和纯文本）的内容，请使用 [GetTemplate](https://docs.aws.amazon.com/ses/latest/APIReference/API_GetTemplate.html) 操作。只有 TemplateName 为必填。

 **导入**。

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

use Aws\Exception\AwsException;
```

 **示例代码** 

```
$SesClient = new Aws\Ses\SesClient([
    'profile' => 'default',
    'version' => '2010-12-01',
    'region' => 'us-east-2'
]);

$name = 'Template_Name';

try {
    $result = $SesClient->getTemplate([
        'TemplateName' => $name,
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    echo $e->getMessage();
    echo "\n";
}
```

## 列出所有电子邮件模板
<a name="list-all-email-templates"></a>

要检索当前 AWS 区域中与您的 AWS 账户 关联的所有电子邮件模板，请使用 [ListTemplates](https://docs.aws.amazon.com/ses/latest/APIReference/API_ListTemplates.html) 操作。

 **导入**。

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

use Aws\Exception\AwsException;
```

 **示例代码** 

```
$SesClient = new Aws\Ses\SesClient([
    'profile' => 'default',
    'version' => '2010-12-01',
    'region' => 'us-east-2'
]);

try {
    $result = $SesClient->listTemplates([
        'MaxItems' => 10,
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    echo $e->getMessage();
    echo "\n";
}
```

## 更新电子邮件模板
<a name="update-an-email-template"></a>

要更改特定电子邮件模板（包括主题行、HTML 正文和纯文本）的内容，请使用 [UpdateTemplate](https://docs.aws.amazon.com/ses/latest/APIReference/API_UpdadteTemplate.html) 操作。

 **导入**。

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

use Aws\Exception\AwsException;
```

 **示例代码** 

```
$SesClient = new Aws\Ses\SesClient([
    'profile' => 'default',
    'version' => '2010-12-01',
    'region' => 'us-east-2'
]);

$name = 'Template_Name';
$html_body = '<h1>AWS Amazon Simple Email Service Test Email</h1>' .
    '<p>This email was sent with <a href="https://aws.amazon.com/ses/">' .
    'Amazon SES</a> using the <a href="https://aws.amazon.com/sdk-for-php/">' .
    'AWS SDK for PHP</a>.</p>';
$subject = 'Amazon SES test (AWS SDK for PHP)';
$plaintext_body = 'This email was send with Amazon SES using the AWS SDK for PHP.';

try {
    $result = $SesClient->updateTemplate([
        'Template' => [
            'HtmlPart' => $html_body,
            'SubjectPart' => $subject,
            'TemplateName' => $name,
            'TextPart' => $plaintext_body,
        ],
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    echo $e->getMessage();
    echo "\n";
}
```

## 删除电子邮件模板
<a name="delete-an-email-template"></a>

要删除特定电子邮件模板，请使用 [DeleteTemplate](https://docs.aws.amazon.com/ses/latest/APIReference/API_DeleteTemplate.html) 操作。您只需要 TemplateName。

 **导入**。

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

use Aws\Exception\AwsException;
```

 **示例代码** 

```
$SesClient = new Aws\Ses\SesClient([
    'profile' => 'default',
    'version' => '2010-12-01',
    'region' => 'us-east-2'
]);

$name = 'Template_Name';

try {
    $result = $SesClient->deleteTemplate([
        'TemplateName' => $name,
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    echo $e->getMessage();
    echo "\n";
}
```

## 使用模板发送电子邮件
<a name="send-an-email-with-a-template"></a>

要使用模板向收件人发送电子邮件，请使用 [SendTemplatedEmail](https://docs.aws.amazon.com/ses/latest/APIReference/API_SendTemplatedEmail.html) 操作。

 **导入**。

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

use Aws\Exception\AwsException;
```

 **示例代码** 

```
$SesClient = new Aws\Ses\SesClient([
    'profile' => 'default',
    'version' => '2010-12-01',
    'region' => 'us-east-2'
]);

$template_name = 'Template_Name';
$sender_email = 'email_address';
$recipient_emails = ['email_address'];

try {
    $result = $SesClient->sendTemplatedEmail([
        'Destination' => [
            'ToAddresses' => $recipient_emails,
        ],
        'ReplyToAddresses' => [$sender_email],
        'Source' => $sender_email,

        'Template' => $template_name,
        'TemplateData' => '{ }'
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    echo $e->getMessage();
    echo "\n";
}
```

# 使用 Amazon SES API 和 适用于 PHP 的 AWS SDK 版本 3 来管理电子邮件筛选条件
<a name="ses-filters"></a>

除了发送电子邮件外，您还可以使用 Amazon Simple Email Service (Amazon SES) 来接收电子邮件。IP 地址筛选条件让您能够选择指定是接受还是拒绝来自某个 IP 地址或 IP 地址范围的邮件。有关更多信息，请参阅[为 Amazon SES 电子邮件接收管理 IP 地址筛选条件](https://docs.aws.amazon.com/ses/latest/DeveloperGuide/receiving-email-managing-ip-filters.html)。

以下示例演示如何：
+ 使用 [CreateReceiptFilter](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-email-2010-12-01.html#createreceiptfilter) 创建电子邮件筛选条件。
+ 使用 [ListReceiptFilters](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-email-2010-12-01.html#listreceiptfilters) 列出所有电子邮件筛选条件。
+ 使用 [DeleteReceiptFilter](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-email-2010-12-01.html#deletereceiptfilter) 删除电子邮件筛选条件。

适用于 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) 中所述。

有关使用 Amazon SES 的更多信息，请参阅 [Amazon SES 开发人员指南](https://docs.aws.amazon.com/ses/latest/DeveloperGuide/)。

## 创建电子邮件筛选条件
<a name="create-an-email-filter"></a>

要允许或阻止来自特定 IP 地址的电子邮件，请使用 [CreateReceiptFilter](https://docs.aws.amazon.com/ses/latest/APIReference/API_CreateReceiptFilter.html) 操作。提供 IP 地址或地址范围以及唯一名称来标识此筛选条件。

 **导入**。

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

use Aws\Exception\AwsException;
```

 **示例代码** 

```
$SesClient = new Aws\Ses\SesClient([
    'profile' => 'default',
    'version' => '2010-12-01',
    'region' => 'us-east-2'
]);

$filter_name = 'FilterName';
$ip_address_range = '10.0.0.1/24';

try {
    $result = $SesClient->createReceiptFilter([
        'Filter' => [
            'IpFilter' => [
                'Cidr' => $ip_address_range,
                'Policy' => 'Block|Allow',
            ],
            'Name' => $filter_name,
        ],
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    echo $e->getMessage();
    echo "\n";
}
```

## 列出所有电子邮件筛选条件
<a name="list-all-email-filters"></a>

要列出当前 AWS 区域中与您的 AWS 账户 关联的 IP 地址筛选条件，请使用 [ListReceiptFilters](https://docs.aws.amazon.com/ses/latest/APIReference/API_ListReceiptFilters.html) 操作。

 **导入**。

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

use Aws\Exception\AwsException;
```

 **示例代码** 

```
$SesClient = new Aws\Ses\SesClient([
    'profile' => 'default',
    'version' => '2010-12-01',
    'region' => 'us-east-2'
]);

try {
    $result = $SesClient->listReceiptFilters();
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    echo $e->getMessage();
    echo "\n";
}
```

## 删除电子邮件筛选条件
<a name="delete-an-email-filter"></a>

要删除特定 IP 地址的现有筛选条件，请使用 [DeleteReceiptFilter](https://docs.aws.amazon.com/ses/latest/APIReference/API_DeleteReceiptFilter.html) 操作。提供唯一筛选条件名称用于标识要删除的接收筛选条件。

如果您需要更改所筛选的地址范围，可以删除接收筛选条件并创建新的筛选条件。

 **导入**。

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

use Aws\Exception\AwsException;
```

 **示例代码** 

```
$SesClient = new Aws\Ses\SesClient([
    'profile' => 'default',
    'version' => '2010-12-01',
    'region' => 'us-east-2'
]);

$filter_name = 'FilterName';

try {
    $result = $SesClient->deleteReceiptFilter([
        'FilterName' => $filter_name,
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    echo $e->getMessage();
    echo "\n";
}
```

# 使用 Amazon SES API 和 适用于 PHP 的 AWS SDK 版本 3 来创建和管理电子邮件规则
<a name="ses-rules"></a>

除了发送电子邮件外，您还可以使用 Amazon Simple Email Service (Amazon SES) 来接收电子邮件。您可以通过接收规则来指定 Amazon SES 在为您拥有的电子邮件地址或域接收电子邮件后，将对这些邮件执行哪些操作。规则可以将电子邮件发送到其他 AWS 服务，包括但不限于 Amazon S3、Amazon SNS 或 AWS Lambda。

有关更多信息，请参阅[为 Amazon SES 电子邮件接收管理接收规则集](https://docs.aws.amazon.com/ses/latest/DeveloperGuide/receiving-email-managing-receipt-rule-sets.html)和[为 Amazon SES 电子邮件接收管理接收规则](https://docs.aws.amazon.com/ses/latest/DeveloperGuide/receiving-email-managing-receipt-rules.html)。

以下示例演示如何：
+ 使用 [CreateReceiptRuleSet](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-email-2010-12-01.html#createreceiptruleset) 创建接收规则集。
+ 使用 [CreateReceiptRule](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-email-2010-12-01.html#createreceiptrule) 创建接收规则。
+ 使用 [DescribeReceiptRuleSet](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-email-2010-12-01.html#describereceiptruleset) 描述接收规则集。
+ 使用 [DescribeReceiptRule](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-email-2010-12-01.html#describereceiptrule) 描述接收规则。
+ 使用 [ListReceiptRuleSets](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-email-2010-12-01.html#listreceiptrulesets) 列出所有接收规则集。
+ 使用 [UpdateReceiptRule](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-email-2010-12-01.html#updatereceiptrule) 更新接收规则。
+ 使用 [DeleteReceiptRule](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-email-2010-12-01.html#deletereceiptrule) 删除接收规则。
+ 使用 [DeleteReceiptRuleSet](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-email-2010-12-01.html#deletereceiptruleset) 删除接收规则集。

适用于 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) 中所述。

有关使用 Amazon SES 的更多信息，请参阅 [Amazon SES 开发人员指南](https://docs.aws.amazon.com/ses/latest/DeveloperGuide/)。

## 创建接收规则集
<a name="create-a-receipt-rule-set"></a>

接收规则集包含接收规则的集合。您必须至少有一个接收规则集与您的账户关联，然后才能创建接收规则。要创建接收规则集，请提供唯一 RuleSetName，然后使用 [CreateReceiptRuleSet](https://docs.aws.amazon.com/ses/latest/APIReference/API_CreateReceiptRuleSet.html) 操作。

 **导入**。

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

use Aws\Exception\AwsException;
```

 **示例代码** 

```
$SesClient = new Aws\Ses\SesClient([
    'profile' => 'default',
    'version' => '2010-12-01',
    'region' => 'us-east-2'
]);

$name = 'Rule_Set_Name';

try {
    $result = $SesClient->createReceiptRuleSet([
        'RuleSetName' => $name,
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    echo $e->getMessage();
    echo "\n";
}
```

## 创建接收规则
<a name="create-a-receipt-rule"></a>

通过添加接收规则到现有接收规则集，控制传入电子邮件。此示例展示了如何创建将传入消息发送到 Amazon S3 存储桶的接收规则，不过您也可以将消息发送到 Amazon SNS 和 AWS Lambda。要创建接收规则，请向 [CreateReceiptRule](https://docs.aws.amazon.com/ses/latest/APIReference/API_CreateReceiptRule.html) 操作提供规则和 RuleSetName。

 **导入**。

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

use Aws\Exception\AwsException;
```

 **示例代码** 

```
$SesClient = new Aws\Ses\SesClient([
    'profile' => 'default',
    'version' => '2010-12-01',
    'region' => 'us-east-2'
]);

$rule_name = 'Rule_Name';
$rule_set_name = 'Rule_Set_Name';
$s3_bucket = 'Bucket_Name';

try {
    $result = $SesClient->createReceiptRule([
        'Rule' => [
            'Actions' => [
                [
                    'S3Action' => [
                        'BucketName' => $s3_bucket,
                    ],
                ],
            ],
            'Name' => $rule_name,
            'ScanEnabled' => true,
            'TlsPolicy' => 'Optional',
            'Recipients' => ['<string>']
        ],
        'RuleSetName' =>  $rule_set_name,

     ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    echo $e->getMessage();
    echo "\n";
}
```

## 描述接收规则集
<a name="describe-a-receipt-rule-set"></a>

每秒一次，返回指定接收规则集的详细信息。要使用 [DescribeReceiptRuleSet](https://docs.aws.amazon.com/ses/latest/APIReference/API_DescribeReceiptRuleSet.html) 操作，请提供 RuleSetName。

 **导入**。

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

use Aws\Exception\AwsException;
```

 **示例代码** 

```
$SesClient = new Aws\Ses\SesClient([
    'profile' => 'default',
    'version' => '2010-12-01',
    'region' => 'us-east-2'
]);

$name = 'Rule_Set_Name';

try {
    $result = $SesClient->describeReceiptRuleSet([
        'RuleSetName' => $name,
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    echo $e->getMessage();
    echo "\n";
}
```

## 描述接收规则
<a name="describe-a-receipt-rule"></a>

返回指定接收规则的详细信息。要使用 [DescribeReceiptRule](https://docs.aws.amazon.com/ses/latest/APIReference/API_DescribeReceiptRule.html) 操作，请提供 RuleName 和 RuleSetName。

 **导入**。

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

use Aws\Exception\AwsException;
```

 **示例代码** 

```
$SesClient = new Aws\Ses\SesClient([
    'profile' => 'default',
    'version' => '2010-12-01',
    'region' => 'us-east-2'
]);

$rule_name = 'Rule_Name';
$rule_set_name = 'Rule_Set_Name';

try {
    $result = $SesClient->describeReceiptRule([
        'RuleName' => $rule_name,
        'RuleSetName' => $rule_set_name,
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    echo $e->getMessage();
    echo "\n";
}
```

## 列出所有接收规则集
<a name="list-all-receipt-rule-sets"></a>

要列出当前 AWS 区域中您 AWS 账户 下存在的接收规则集，请使用 [ListReceiptRuleSets](https://docs.aws.amazon.com/ses/latest/APIReference/API_ListReceiptRuleSets.html) 操作。

 **导入**。

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

use Aws\Exception\AwsException;
```

 **示例代码** 

```
$SesClient = new Aws\Ses\SesClient([
    'profile' => 'default',
    'version' => '2010-12-01',
    'region' => 'us-east-2'
]);

try {
    $result = $SesClient->listReceiptRuleSets();
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    echo $e->getMessage();
    echo "\n";
}
```

## 更新接收规则
<a name="update-a-receipt-rule"></a>

此示例展示了如何更新将传入消息发送到 AWS Lambda 函数的接收规则，不过您也可以将消息发送到 Amazon SNS 和 Amazon S3。要使用 [UpdateReceiptRule](https://docs.aws.amazon.com/ses/latest/APIReference/API_UpdateReceiptRule.html) 操作，请提供新接收规则和 RuleSetName。

 **导入**。

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

use Aws\Exception\AwsException;
```

 **示例代码** 

```
$SesClient = new Aws\Ses\SesClient([
    'profile' => 'default',
    'version' => '2010-12-01',
    'region' => 'us-east-2'
]);

$rule_name = 'Rule_Name';
$rule_set_name = 'Rule_Set_Name';
$lambda_arn = 'Amazon Resource Name (ARN) of the AWS Lambda function';
$sns_topic_arn = 'Amazon Resource Name (ARN) of the Amazon SNS topic';

try {
    $result = $SesClient->updateReceiptRule([
        'Rule' => [
            'Actions' => [
                'LambdaAction' => [
                    'FunctionArn' => $lambda_arn,
                    'TopicArn' => $sns_topic_arn,
                ],
            ],
            'Enabled' => true,
            'Name' => $rule_name,
            'ScanEnabled' => false,
            'TlsPolicy' => 'Require',
        ],
        'RuleSetName' => $rule_set_name,
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    echo $e->getMessage();
    echo "\n";
}
```

## 删除接收规则集
<a name="delete-a-receipt-rule-set"></a>

删除当前未禁用的指定接收规则集。这还会删除其中包含的所有接收规则。要删除接收规则集，请向 [DeleteReceiptRuleSet](https://docs.aws.amazon.com/ses/latest/APIReference/API_DeleteReceiptRuleSet.html) 操作提供 RuleSetName。

 **导入**。

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

use Aws\Exception\AwsException;
```

 **示例代码** 

```
$SesClient = new Aws\Ses\SesClient([
    'profile' => 'default',
    'version' => '2010-12-01',
    'region' => 'us-east-2'
]);

$name = 'Rule_Set_Name';

try {
    $result = $SesClient->deleteReceiptRuleSet([
        'RuleSetName' => $name,
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    echo $e->getMessage();
    echo "\n";
}
```

## 删除接收规则
<a name="delete-a-receipt-rule"></a>

要删除指定的接收规则，请向 [DeleteReceiptRule](https://docs.aws.amazon.com/ses/latest/APIReference/API_DeleteReceiptRule.html) 操作提供 RuleName 和 RuleSetName。

 **导入**。

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

use Aws\Exception\AwsException;
```

 **示例代码** 

```
$SesClient = new Aws\Ses\SesClient([
    'profile' => 'default',
    'version' => '2010-12-01',
    'region' => 'us-east-2'
]);

$rule_name = 'Rule_Name';
$rule_set_name = 'Rule_Set_Name';

try {
    $result = $SesClient->deleteReceiptRule([
        'RuleName' => $rule_name,
        'RuleSetName' => $rule_set_name,
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    echo $e->getMessage();
    echo "\n";
}
```

# 使用 Amazon SES API 和 适用于 PHP 的 AWS SDK 版本 3 来监控发送活动
<a name="ses-send-email"></a>

Amazon Simple Email Service (Amazon SES) 提供了监控发送活动的方法。我们建议您实现这些方法，以便您可以跟踪重要的指标，如您账户的邮件退回率、投诉率和拒绝率。过高的退回邮件率和投诉率可能会影响您使用 Amazon SES 发送电子邮件的能力。

以下示例演示如何：
+ 使用 [GetSendQuota](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-email-2010-12-01.html#getsendquota) 检查您的发送配额。
+ 使用 [GetSendStatistics](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-email-2010-12-01.html#getsendstatistics) 监控您的发送活动。

适用于 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) 中所述。

有关使用 Amazon SES 的更多信息，请参阅 [Amazon SES 开发人员指南](https://docs.aws.amazon.com/ses/latest/DeveloperGuide/)。

## 检查发送配额
<a name="check-your-sending-quota"></a>

在单个 24 小时期间，您只能发送特定数量的邮件。要检查仍然允许您发送多少邮件，请使用 [GetSendQuota](https://docs.aws.amazon.com/ses/latest/APIReference/API_GetSendQuota.html) 操作。有关更多信息，请参阅 [管理 Amazon SES 发送限制](https://docs.aws.amazon.com/ses/latest/DeveloperGuide/manage-sending-limits.html)。

 **导入**。

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

use Aws\Exception\AwsException;
use Aws\Ses\SesClient;
```

 **示例代码** 

```
$SesClient = new SesClient([
    'profile' => 'default',
    'version' => '2010-12-01',
    'region' => 'us-east-1'

]);

try {
    $result = $SesClient->getSendQuota();
    $send_limit = $result["Max24HourSend"];
    $sent = $result["SentLast24Hours"];
    $available = $send_limit - $sent;
    print("<p>You can send " . $available . " more messages in the next 24 hours.</p>");
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    echo $e->getMessage();
    echo "\n";
}
```

## 监控发送活动
<a name="monitor-your-sending-activity"></a>

要检索您在过去两周内发送的邮件的指标，请使用 [GetSendStatistics](https://docs.aws.amazon.com/ses/latest/APIReference/API_GetSendStatistics.html) 操作。此示例以 15 分钟为增量，返回传送尝试的次数、退回邮件数、投诉邮件数和拒绝邮件数。

 **导入**。

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

use Aws\Exception\AwsException;
use Aws\Ses\SesClient;
```

 **示例代码** 

```
$SesClient = new SesClient([
    'profile' => 'default',
    'version' => '2010-12-01',
    'region' => 'us-east-1'
]);

try {
    $result = $SesClient->getSendStatistics();
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    echo $e->getMessage();
    echo "\n";
}
```

# 使用 Amazon SES API 和 适用于 PHP 的 AWS SDK 版本 3 来向发件人授权
<a name="ses-sender-policy"></a>

要允许其他 AWS 账户、AWS Identity and Access Management 用户或 AWS 服务可代表您通过 Amazon Simple Email Service (Amazon SES) 发送电子邮件，您需要创建发送授权策略。这是一个附加到您拥有的身份的 JSON 文档。

该策略明确列出您允许哪些人、在何种条件下使用该身份。除了您以及在策略中明确授予权限的实体之外，所有其他发件人不允许发送电子邮件。一个身份可以不附加策略、附加一个策略或附加多个策略。此外，您还可以使用一个包含多个语句的策略来实现多个策略的效果。

有关更多信息，请参阅[使用 Amazon SES 的发送授权](https://docs.aws.amazon.com/ses/latest/DeveloperGuide/sending-authorization.html)。

以下示例演示如何：
+ 使用 [PutIdentityPolicy](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-email-2010-12-01.html#createidentitypolicy) 创建授权发件人。
+ 使用 [GetIdentityPolicies](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-email-2010-12-01.html#getidentitypolicies) 检索授权发件人的策略。
+ 使用 [ListIdentityPolicies](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-email-2010-12-01.html#listidentitypolicies) 列出授权发件人。
+ 使用 [DeleteIdentityPolicy](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-email-2010-12-01.html#deleteidentitypolicy) 撤销授权发件人的权限。

适用于 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) 中所述。

有关使用 Amazon SES 的更多信息，请参阅 [Amazon SES 开发人员指南](https://docs.aws.amazon.com/ses/latest/DeveloperGuide/)。

## 创建授权发件人
<a name="create-an-authorized-sender"></a>

要授权其他 AWS 账户 代表您发送电子邮件，请使用身份授权策略添加或更新授权，以允许从您经过验证的电子邮件地址或域发送电子邮件。要创建身份策略，请使用 [PutIdentityPolicy](https://docs.aws.amazon.com/ses/latest/APIReference/API_PutIdentityPolicy.html) 操作。

 **导入**。

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

use Aws\Exception\AwsException;
use Aws\Ses\SesClient;
```

 **示例代码** 

```
$SesClient = new SesClient([
    'profile' => 'default',
    'version' => '2010-12-01',
    'region' => 'us-east-1'
]);

$identity = "arn:aws:ses:us-east-1:123456789012:identity/example.com";
$other_aws_account = "0123456789";
$policy = <<<EOT
{
  "Id":"ExampleAuthorizationPolicy",
  "Version":"2012-10-17",		 	 	 
  "Statement":[
    {
      "Sid":"AuthorizeAccount",
      "Effect":"Allow",
      "Resource":"$identity",
      "Principal":{
        "AWS":[ "$other_aws_account" ]
      },
      "Action":[
        "SES:SendEmail",
        "SES:SendRawEmail"
      ]
    }
  ]
}
EOT;
$name = "policyName";

try {
    $result = $SesClient->putIdentityPolicy([
        'Identity' => $identity,
        'Policy' => $policy,
        'PolicyName' => $name,
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    echo $e->getMessage();
    echo "\n";
}
```

## 检索授权发件人的策略
<a name="retrieve-polices-for-an-authorized-sender"></a>

返回与特定电子邮件身份或域身份关联的发送授权策略。要获取指定电子邮件地址或域的发送授权，请使用 [GetIdentityPolicy](https://docs.aws.amazon.com/ses/latest/APIReference/API_GetIdentityPolicy.html) 操作。

 **导入**。

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

use Aws\Exception\AwsException;
use Aws\Ses\SesClient;
```

 **示例代码** 

```
$SesClient = new SesClient([
    'profile' => 'default',
    'version' => '2010-12-01',
    'region' => 'us-east-1'
]);

$identity = "arn:aws:ses:us-east-1:123456789012:identity/example.com";
$policies = ["policyName"];

try {
    $result = $SesClient->getIdentityPolicies([
        'Identity' => $identity,
        'PolicyNames' => $policies,
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    echo $e->getMessage();
    echo "\n";
}
```

## 列出授权发件人
<a name="list-authorized-senders"></a>

在当前 AWS 区域中，要列出与特定电子邮件身份或域关联的发送授权策略，请使用 [ListIdentityPolicies](https://docs.aws.amazon.com/ses/latest/APIReference/API_ListIdentityPolicies.html) 操作。

 **导入**。

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

use Aws\Exception\AwsException;
use Aws\Ses\SesClient;
```

 **示例代码** 

```
$SesClient = new SesClient([
    'profile' => 'default',
    'version' => '2010-12-01',
    'region' => 'us-east-1'
]);

$identity = "arn:aws:ses:us-east-1:123456789012:identity/example.com";

try {
    $result = $SesClient->listIdentityPolicies([
        'Identity' => $identity,
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    echo $e->getMessage();
    echo "\n";
}
```

## 撤销授权发件人的权限
<a name="revoke-permission-for-an-authorized-sender"></a>

使用 [DeleteIdentityPolicy](https://docs.aws.amazon.com/ses/latest/APIReference/API_DeleteIdentityPolicy.html) 操作，通过删除关联的身份策略，删除其他 AWS 账户 通过电子邮件身份或域身份发送电子邮件的发送授权。

 **导入**。

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

use Aws\Exception\AwsException;
use Aws\Ses\SesClient;
```

 **示例代码** 

```
$SesClient = new SesClient([
    'profile' => 'default',
    'version' => '2010-12-01',
    'region' => 'us-east-1'
]);

$identity = "arn:aws:ses:us-east-1:123456789012:identity/example.com";
$name = "policyName";

try {
    $result = $SesClient->deleteIdentityPolicy([
        'Identity' => $identity,
        'PolicyName' => $name,
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    echo $e->getMessage();
    echo "\n";
}
```

# 使用版本 3 的亚马逊 SNS 示 适用于 PHP 的 AWS SDK 例
<a name="sns-examples"></a>

Amazon Simple Notification Service (Amazon SNS) 是一项 Web 服务，用于协调和管理向订阅端点或客户端交付或发送消息的过程。

在 Amazon SNS 中有两种类型的客户端：发布者（也称为创建者）和订阅用户（也称为用户）。发布者通过创建消息并将消息发送至主题与订阅者进行异步交流，主题是一个逻辑访问点和通信渠道。订阅者（Web 服务器、电子邮件地址、Amazon SQS 队列、 AWS Lambda 函数）在订阅主题时通过支持的协议之一（Amazon SQS HTTP/HTTPS URLs、、电子邮件 AWS SMS、Lambda）使用或接收消息或通知。

 适用于 PHP 的 AWS SDK 版本 3 的所有示例代码都可以在[此处找到 GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code)。

**Topics**
+ [管理主题](sns-examples-managing-topics.md)
+ [管理订阅](sns-examples-subscribing-unsubscribing-topics.md)
+ [发送 Amazon SMS 消息](sns-examples-sending-sms.md)

# 在使用 适用于 PHP 的 AWS SDK 版本 3 的 Amazon SNS 中管理主题
<a name="sns-examples-managing-topics"></a>

要将通知发送到 Amazon Simple Queue Service (Amazon SQS)、HTTP/HTTPS URL、电子邮件、AWS SMS 或 AWS Lambda，您必须首先创建主题，以管理该主题的任何订阅用户的消息传送。

对于观察程序设计模式，此主题 (Topic) 类似于该主题 (Subject)。创建主题后，您可以添加在有消息发布到该主题时将自动通知的订阅者。

在[在使用 适用于 PHP 的 AWS SDK 版本 3 的 Amazon SNS 中管理订阅](sns-examples-subscribing-unsubscribing-topics.md)中了解有关订阅主题的更多信息。

以下示例演示如何：
+ 使用 [CreateTopic](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-sns-2010-03-31.html#createtopic) 创建将通知发布到的主题。
+ 使用 [ListTopics](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-sns-2010-03-31.html#listtopic) 返回请求者的主题列表。
+ 使用 [DeleteTopic](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-sns-2010-03-31.html#deletetopic) 删除主题及其所有订阅。
+ 使用 [GetTopicAttributes](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-sns-2010-03-31.html#gettopicattributes) 返回主题的所有属性。
+ 使用 [SetTopicAttributes](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-sns-2010-03-31.html#settopicattributes) 允许主题所有者将主题的属性设置为新值。

有关使用 Amazon SNS 的更多信息，请参阅[用于消息传输状态的 Amazon SNS 主题属性](https://docs.aws.amazon.com/sns/latest/dg/sns-topic-attributes.html)。

适用于 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) 中所述。

## 创建主题
<a name="create-a-topic"></a>

要创建主题，请使用 [CreateTopic](https://docs.aws.amazon.com/sns/latest/api/API_CreateTopic.html) 操作。

您 AWS 账户 中的各个主题名称必须唯一。

 **导入**。

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

use Aws\Exception\AwsException;
use Aws\Sns\SnsClient;
```

 **示例代码** 

```
$SnSclient = new SnsClient([
    'profile' => 'default',
    'region' => 'us-east-1',
    'version' => '2010-03-31'
]);

$topicname = 'myTopic';

try {
    $result = $SnSclient->createTopic([
        'Name' => $topicname,
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    error_log($e->getMessage());
}
```

## 列出主题
<a name="list-your-topics"></a>

要列出当前 AWS 区域中的最多 100 个现有主题，请使用 [ListTopics](https://docs.aws.amazon.com/sns/latest/api/API_ListTopics.html) 操作。

 **导入**。

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

use Aws\Exception\AwsException;
use Aws\Sns\SnsClient;
```

 **示例代码** 

```
$SnSclient = new SnsClient([
    'profile' => 'default',
    'region' => 'us-east-1',
    'version' => '2010-03-31'
]);

try {
    $result = $SnSclient->listTopics();
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    error_log($e->getMessage());
}
```

## 删除主题
<a name="delete-a-topic"></a>

要删除现有主题及其所有订阅，请使用 [DeleteTopic](https://docs.aws.amazon.com/sns/latest/api/API_DeleteTopic.html) 操作。

尚未传送至订阅者的任何消息也将删除。

 **导入**。

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

use Aws\Exception\AwsException;
use Aws\Sns\SnsClient;
```

 **示例代码** 

```
$SnSclient = new SnsClient([
    'profile' => 'default',
    'region' => 'us-east-1',
    'version' => '2010-03-31'
]);

$topic = 'arn:aws:sns:us-east-1:111122223333:MyTopic';

try {
    $result = $SnSclient->deleteTopic([
        'TopicArn' => $topic,
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    error_log($e->getMessage());
}
```

## 获取主题属性
<a name="get-topic-attributes"></a>

要检索单个现有主题的属性，请使用 [GetTopicAttributes](https://docs.aws.amazon.com/sns/latest/api/API_GetTopicAttributes.html) 操作。

 **导入**。

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

use Aws\Exception\AwsException;
use Aws\Sns\SnsClient;
```

 **示例代码** 

```
$SnSclient = new SnsClient([
    'profile' => 'default',
    'region' => 'us-east-1',
    'version' => '2010-03-31'
]);

$topic = 'arn:aws:sns:us-east-1:111122223333:MyTopic';

try {
    $result = $SnSclient->getTopicAttributes([
        'TopicArn' => $topic,
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    error_log($e->getMessage());
}
```

## 设置主题属性
<a name="set-topic-attributes"></a>

要更新单个现有主题的属性，请使用 [SetTopicAttributes](https://docs.aws.amazon.com/sns/latest/api/API_SetTopicAttributes.html) 操作。

您只能设置 `Policy`、`DisplayName` 和 `DeliveryPolicy` 属性。

 **导入**。

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

use Aws\Exception\AwsException;
use Aws\Sns\SnsClient;
```

 **示例代码** 

```
$SnSclient = new SnsClient([
    'profile' => 'default',
    'region' => 'us-east-1',
    'version' => '2010-03-31'
]);
$attribute = 'Policy | DisplayName | DeliveryPolicy';
$value = 'First Topic';
$topic = 'arn:aws:sns:us-east-1:111122223333:MyTopic';

try {
    $result = $SnSclient->setTopicAttributes([
        'AttributeName' => $attribute,
        'AttributeValue' => $value,
        'TopicArn' => $topic,
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    error_log($e->getMessage());
}
```

# 使用 适用于 PHP 的 AWS SDK 版本 3 在 Amazon SNS 中管理订阅
<a name="sns-examples-subscribing-unsubscribing-topics"></a>

使用亚马逊简单通知服务 (Amazon SNS) Simple Notification 主题向亚马逊简单队列服务 (Amazon SQS)、HTTP/HTTPS、电子邮件地址、() 或发送通知。 AWS Server Migration Service AWS SMS AWS Lambda

订阅将附加到某个主题，该主题管理将消息发送给订阅者。要详细了解如何在 [Amazon SNS 中使用 适用于 PHP 的 AWS SDK 版本 3 创建主题](sns-examples-managing-topics.md)。

以下示例演示如何：
+ 使用 [Subscribe](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-sns-2010-03-31.html#subscribe) 订阅到现有主题。
+ 使用验证订阅[ConfirmSubscription](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-sns-2010-03-31.html#confirmsubscription)。
+ 使用列出现有订阅[ListSubscriptionsByTopic](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-sns-2010-03-31.html#listsubscriptionsbytopic)。
+ 使用 [Unsubscribe](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-sns-2010-03-31.html#unsubscribe) 删除订阅。
+ 使用 [publish](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-sns-2010-03-31.html#publish) 将消息发送给某一主题的所有订阅者。

有关使用亚马逊 SNS 的更多信息，请参阅[使用亚马逊 SNS 发送消息](https://docs.aws.amazon.com/sns/latest/dg/sns-system-to-system-messaging.html)。 System-to-System

的所有示例代码都可以在[此 适用于 PHP 的 AWS SDK 处找到 GitHub](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)。

## 针对主题订阅电子邮件地址
<a name="subscribe-an-email-address-to-a-topic"></a>

要建立电子邮件地址订阅，请使用 [Subscribe](https://docs.aws.amazon.com/sns/latest/api/API_Subscribe.html) 操作。

您可以使用订阅方法，根据在所传递参数中使用的值，将多种不同的端点订阅到某个 Amazon SNS 主题。本主题中的其他示例演示了这一点。

在本示例中，端点是电子邮件地址。将向该电子邮件发送确认令牌。在收到电子邮件的 3 天内，使用此确认令牌验证订阅。

 **导入** 

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

use Aws\Exception\AwsException;
use Aws\Sns\SnsClient;
```

 **示例代码** 

```
$SnSclient = new SnsClient([
    'profile' => 'default',
    'region' => 'us-east-1',
    'version' => '2010-03-31'
]);

$protocol = 'email';
$endpoint = 'sample@example.com';
$topic = 'arn:aws:sns:us-east-1:111122223333:MyTopic';

try {
    $result = $SnSclient->subscribe([
        'Protocol' => $protocol,
        'Endpoint' => $endpoint,
        'ReturnSubscriptionArn' => true,
        'TopicArn' => $topic,
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    error_log($e->getMessage());
}
```

## 将应用程序端点订阅到主题
<a name="subscribe-an-application-endpoint-to-a-topic"></a>

要建立 Web 应用程序订阅，请使用 [Subscribe](https://docs.aws.amazon.com/sns/latest/api/API_Subscribe.html) 操作。

您可以使用订阅方法，根据在所传递参数中使用的值，将多种不同的端点订阅到某个 Amazon SNS 主题。本主题中的其他示例演示了这一点。

在此示例中，端点是 URL。将会向此 Web 地址发送确认令牌。在收到电子邮件的 3 天内，使用此确认令牌验证订阅。

 **导入** 

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

use Aws\Exception\AwsException;
use Aws\Sns\SnsClient;
```

 **示例代码** 

```
$SnSclient = new SnsClient([
    'profile' => 'default',
    'region' => 'us-east-1',
    'version' => '2010-03-31'
]);

$protocol = 'https';
$endpoint = 'https://';
$topic = 'arn:aws:sns:us-east-1:111122223333:MyTopic';

try {
    $result = $SnSclient->subscribe([
        'Protocol' => $protocol,
        'Endpoint' => $endpoint,
        'ReturnSubscriptionArn' => true,
        'TopicArn' => $topic,
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    error_log($e->getMessage());
}
```

## 向主题订阅 Lambda 函数
<a name="subscribe-a-lam-function-to-a-topic"></a>

要建立 Lambda 函数订阅，请使用 [Subscribe](https://docs.aws.amazon.com/sns/latest/api/API_Subscribe.html) 操作。

您可以使用订阅方法，根据在所传递参数中使用的值，将多种不同的端点订阅到某个 Amazon SNS 主题。本主题中的其他示例演示了这一点。

在此示例中，端点是 Lambda 函数。将会向此 Lambda 函数发送确认令牌。在收到电子邮件的 3 天内，使用此确认令牌验证订阅。

 **导入** 

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

use Aws\Exception\AwsException;
use Aws\Sns\SnsClient;
```

 **示例代码** 

```
$SnSclient = new SnsClient([
    'profile' => 'default',
    'region' => 'us-east-1',
    'version' => '2010-03-31'
]);

$protocol = 'lambda';
$endpoint = 'arn:aws:lambda:us-east-1:123456789023:function:messageStore';
$topic = 'arn:aws:sns:us-east-1:111122223333:MyTopic';

try {
    $result = $SnSclient->subscribe([
        'Protocol' => $protocol,
        'Endpoint' => $endpoint,
        'ReturnSubscriptionArn' => true,
        'TopicArn' => $topic,
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    error_log($e->getMessage());
}
```

## 将文本 SMS 订阅到主题
<a name="subscribe-a-text-sms-to-a-topic"></a>

要同时将 SMS 消息发送到多个电话号码，请将各个号码订阅到主题。

要建立电话号码订阅，请使用 [Subscribe](https://docs.aws.amazon.com/sns/latest/api/API_Subscribe.html) 操作。

您可以使用订阅方法，根据在所传递参数中使用的值，将多种不同的端点订阅到某个 Amazon SNS 主题。本主题中的其他示例演示了这一点。

在此示例中，端点是 E.164 格式的电话号码，这是国际电信的标准。

将会向此电话号码发送确认令牌。在收到电子邮件的 3 天内，使用此确认令牌验证订阅。

有关使用 Amazon SNS 发送 SMS 消息的替代方法，请参阅[在使用 适用于 PHP 的 AWS SDK 版本 3 的 Amazon SNS 中发送 SMS 消息](sns-examples-sending-sms.md)。

 **导入** 

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

use Aws\Exception\AwsException;
use Aws\Sns\SnsClient;
```

 **示例代码** 

```
$SnSclient = new SnsClient([
    'profile' => 'default',
    'region' => 'us-east-1',
    'version' => '2010-03-31'
]);

$protocol = 'sms';
$endpoint = '+1XXX5550100';
$topic = 'arn:aws:sns:us-east-1:111122223333:MyTopic';

try {
    $result = $SnSclient->subscribe([
        'Protocol' => $protocol,
        'Endpoint' => $endpoint,
        'ReturnSubscriptionArn' => true,
        'TopicArn' => $topic,
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    error_log($e->getMessage());
}
```

## 确认订阅到主题
<a name="confirm-subscription-to-a-topic"></a>

要实际创建订阅，端点所有者必须使用在最初建立订阅时发送的令牌，确认接收来自该主题的消息的意图，如前所述。确认令牌有效期为 3 天。3 天之后，您可以通过创建新订阅来重新发送令牌。

要确认订阅，请使用[ConfirmSubscription](https://docs.aws.amazon.com/sns/latest/api/API_ConfirmSubscription.html)操作。

 **导入** 

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

use Aws\Exception\AwsException;
use Aws\Sns\SnsClient;
```

 **示例代码** 

```
$SnSclient = new SnsClient([
    'profile' => 'default',
    'region' => 'us-east-1',
    'version' => '2010-03-31'
]);

$subscription_token = 'arn:aws:sns:us-east-1:111122223333:MyTopic:123456-abcd-12ab-1234-12ba3dc1234a';
$topic = 'arn:aws:sns:us-east-1:111122223333:MyTopic';

try {
    $result = $SnSclient->confirmSubscription([
        'Token' => $subscription_token,
        'TopicArn' => $topic,
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    error_log($e->getMessage());
}
```

## 列出对主题的订阅
<a name="list-subscriptions-to-a-topic"></a>

要列出给定 AWS 区域中最多 100 个现有订阅，请使用[ListSubscriptions](https://docs.aws.amazon.com/sns/latest/api/API_ListSubscriptions.html)操作。

 **导入** 

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

use Aws\Exception\AwsException;
use Aws\Sns\SnsClient;
```

 **示例代码** 

```
$SnSclient = new SnsClient([
    'profile' => 'default',
    'region' => 'us-east-1',
    'version' => '2010-03-31'
]);

try {
    $result = $SnSclient->listSubscriptions();
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    error_log($e->getMessage());
}
```

## 取消订阅主题
<a name="unsubscribe-from-a-topic"></a>

要删除订阅到某个主题的端点，请使用 [Unsubscribe](https://docs.aws.amazon.com/sns/latest/api/API_Unsubscribe.html) 操作。

如果订阅需要身份验证才能删除，则只有订阅的所有者或主题的所有者可以取消订阅，并且需要 AWS 签名。如果取消订阅调用无需身份验证，并且请求者不是订阅所有者，则会将一条最终取消消息传送到端点。

 **导入** 

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

use Aws\Exception\AwsException;
use Aws\Sns\SnsClient;
```

 **示例代码** 

```
$SnSclient = new SnsClient([
    'profile' => 'default',
    'region' => 'us-east-1',
    'version' => '2010-03-31'
]);

$subscription = 'arn:aws:sns:us-east-1:111122223333:MySubscription';

try {
    $result = $SnSclient->unsubscribe([
        'SubscriptionArn' => $subscription,
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    error_log($e->getMessage());
}
```

## 向 Amazon SNS 主题发布消息
<a name="publish-a-message-to-an-sns-topic"></a>

要将消息发送到订阅到某个 Amazon SNS 主题的各个端点，请使用 [Publish](https://docs.aws.amazon.com/sns/latest/api/API_Publish.html) 操作。

创建包含用于发布消息的参数的对象，包括消息文本以及 Amazon SNS 主题的 Amazon 资源名称 (ARN)。

 **导入** 

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

use Aws\Exception\AwsException;
use Aws\Sns\SnsClient;
```

 **示例代码** 

```
$SnSclient = new SnsClient([
    'profile' => 'default',
    'region' => 'us-east-1',
    'version' => '2010-03-31'
]);

$message = 'This message is sent from a Amazon SNS code sample.';
$topic = 'arn:aws:sns:us-east-1:111122223333:MyTopic';

try {
    $result = $SnSclient->publish([
        'Message' => $message,
        'TopicArn' => $topic,
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    error_log($e->getMessage());
}
```

# 在使用 适用于 PHP 的 AWS SDK 版本 3 的 Amazon SNS 中发送 SMS 消息
<a name="sns-examples-sending-sms"></a>

您可以使用 Amazon Simple Notification Service (Amazon SNS) 来将文本消息或 SMS 消息发送到支持 SMS 的设备上。您可以直接向电话号码发送消息，也可以使用多个电话号码订阅主题，然后通过向该主题发送消息来一次向这些电话号码发送消息。

使用 Amazon SNS 来指定发送 SMS 消息的首选项，例如如何优化消息传输（在成本或可靠传输方面）、您的每月支出限额、如何记录消息传输以及是否要订阅每日 SMS 使用率报告。这些首选项通过检索得到，并设置为 Amazon SNS 的 SMS 属性。

在发送 SMS 消息时，请使用 E.164 格式指定电话号码。E.164 是国际电信的标准电话号码结构。采用此格式的电话号码最多可包含 15 位数字，并以加号 (\$1) 和国家代码作为前缀。例如，E.164 格式的美国电话号码将显示为 \$11001XXX5550100。

以下示例演示如何：
+ 使用 [GetSMSAttributes](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-sns-2010-03-31.html#getsmsattributes) 检索从您账户发送 SMS 消息的默认设置。
+ 使用 [SetSMSAttributes](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-sns-2010-03-31.html#setsmsattributes) 更新从您账户发送 SMS 消息的默认设置。
+ 使用 [CheckIfPhoneNumberISOptedOut](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-sns-2010-03-31.html#checkifphonenumberisoptedout) 确定指定电话所有者是否已选择不接收来自您账户的 SMS 消息。
+ 使用 [ListPhoneNumberOptedOut](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-sns-2010-03-31.html#listphonenumbersoptedout) 列出其所有者已选择不接收来自您账户的 SMS 消息的电话号码。
+ 使用 [Publish](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-sns-2010-03-31.html#publish) 直接将文本消息（SMS 消息）发送到电话号码。

有关使用 Amazon SNS 的更多信息，请参阅[将手机号码作为订阅用户，将 Amazon SNS 用于用户通知（发送 SMS）](https://docs.aws.amazon.com/sns/latest/dg/sns-mobile-phone-number-as-subscriber.html)。

适用于 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) 中所述。

## 获取 SMS 属性
<a name="get-sms-attributes"></a>

要检索 SMS 消息的默认设置，请使用 [GetSMSAttributes](https://docs.aws.amazon.com/sns/latest/api/API_GetSMSAttributes.html) 操作。

此示例获取 `DefaultSMSType` 属性。此属性控制 SMS 消息是作为 `Promotional` 发送（这将优化消息传送以尽可能降低成本）还是作为 `Transactional` 发送（这将优化消息传送以实现最高的可靠性）。

 **导入**。

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

use Aws\Exception\AwsException;
use Aws\Sns\SnsClient;
```

 **示例代码** 

```
$SnSclient = new SnsClient([
    'profile' => 'default',
    'region' => 'us-east-1',
    'version' => '2010-03-31'
]);

try {
    $result = $SnSclient->getSMSAttributes([
        'attributes' => ['DefaultSMSType'],
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    error_log($e->getMessage());
}
```

## 设置 SMS 属性
<a name="set-sms-attributes"></a>

要更新 SMS 消息的默认设置，请使用 [SetSMSAttributes](https://docs.aws.amazon.com/sns/latest/api/API_SetSMSAttributes.html) 操作。

此示例将 `DefaultSMSType` 属性设置为 `Transactional`，这会优化消息传送以实现最高的可靠性。

 **导入**。

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

use Aws\Exception\AwsException;
use Aws\Sns\SnsClient;
```

 **示例代码** 

```
$SnSclient = new SnsClient([
    'profile' => 'default',
    'region' => 'us-east-1',
    'version' => '2010-03-31'
]);

try {
    $result = $SnSclient->SetSMSAttributes([
        'attributes' => [
            'DefaultSMSType' => 'Transactional',
        ],
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    error_log($e->getMessage());
}
```

## 检查电话号码是否已选择不接收消息
<a name="check-if-a-phone-number-has-opted-out"></a>

要确定指定电话所有者是否已选择不接收来自您账户的 SMS 消息，请使用 [CheckIfPhoneNumberIsOptedOut](https://docs.aws.amazon.com/sns/latest/api/API_CheckIfPhoneNumberIsOptedOut.html) 操作。

在此示例中，电话号码为 E.164 格式，这是国际电信的标准。

 **导入**。

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

use Aws\Exception\AwsException;
use Aws\Sns\SnsClient;
```

 **示例代码** 

```
$SnSclient = new SnsClient([
    'profile' => 'default',
    'region' => 'us-east-1',
    'version' => '2010-03-31'
]);

$phone = '+1XXX5550100';

try {
    $result = $SnSclient->checkIfPhoneNumberIsOptedOut([
        'phoneNumber' => $phone,
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    error_log($e->getMessage());
}
```

## 列出选择不接收消息的电话号码
<a name="list-opted-out-phone-numbers"></a>

要检索其所有者已选择不接收来自您账户的 SMS 消息的电话号码列表，请使用 [ListPhoneNumbersOptedOut](https://docs.aws.amazon.com/sns/latest/api/API_ListPhoneNumbersOptedOut.html) 操作。

 **导入**。

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

use Aws\Exception\AwsException;
use Aws\Sns\SnsClient;
```

 **示例代码** 

```
$SnSclient = new SnsClient([
    'profile' => 'default',
    'region' => 'us-east-1',
    'version' => '2010-03-31'
]);

try {
    $result = $SnSclient->listPhoneNumbersOptedOut();
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    error_log($e->getMessage());
}
```

## 发布到文本消息（SMS 消息）
<a name="publish-to-a-text-message-sms-message"></a>

要将文本消息（SMS 消息）直接传送到电话号码，请使用 [Publish](https://docs.aws.amazon.com/sns/latest/api/API_Publish.html) 操作。

在此示例中，电话号码为 E.164 格式，这是国际电信的标准。

SMS 消息最多可以包含 140 个字节。单个 SMS 发布操作的大小限制为 1600 字节。

有关发送 SMS 消息的更多详细信息，请参阅[发送 SMS 消息](https://docs.aws.amazon.com/sns/latest/dg/sms_publish-to-phone.html)。

 **导入**。

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

use Aws\Exception\AwsException;
use Aws\Sns\SnsClient;
```

 **示例代码** 

```
$SnSclient = new SnsClient([
    'profile' => 'default',
    'region' => 'us-east-1',
    'version' => '2010-03-31'
]);

$message = 'This message is sent from a Amazon SNS code sample.';
$phone = '+1XXX5550100';

try {
    $result = $SnSclient->publish([
        'Message' => $message,
        'PhoneNumber' => $phone,
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    error_log($e->getMessage());
}
```

# 使用 适用于 PHP 的 AWS SDK 版本 3 的 Amazon SQS 示例
<a name="sqs-examples"></a>

Amazon Simple Queue Service (SQS) 是一种快速、可靠、可扩展且完全托管的消息队列服务。Amazon SQS 使您能够分离云应用程序的组件。Amazon SQS 包括具有高吞吐量和“至少一次”处理的标准队列，以及提供 FIFO（先进先出）交付和“仅一次”处理的 FIFO 队列。

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

**Topics**
+ [启用长轮询](sqs-examples-enable-long-polling.md)
+ [管理可见性超时](sqs-examples-managing-visibility-timeout.md)
+ [发送和接收消息](sqs-examples-send-receive-messages.md)
+ [使用死信队列](sqs-examples-dead-letter-queues.md)
+ [使用队列](sqs-examples-using-queues.md)

# 在使用 适用于 PHP 的 AWS SDK 版本 3 的 Amazon SQS 中启用长轮询
<a name="sqs-examples-enable-long-polling"></a>

在发送响应之前，长轮询使 Amazon SQS 等待指定的时间，以便消息在队列中变得可用，从而减少空响应的数量。此外，长轮询通过查询所有服务器而不是执行服务器采样，消除了假的空响应。要启用长轮询，请为接收的消息指定不为零的等待时间。要了解更多信息，请参阅 [SQS 长轮询](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-long-polling.html)。

以下示例演示如何：
+ 使用 [SetQueueAttributes](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-sqs-2012-11-05.html#setqueueattributes) 设置 Amazon SQS 队列的属性，以启用长轮询。
+ 使用 [ReceiveMessage](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-sqs-2012-11-05.html#receivemessage) 借助长轮询检索一条或多条消息。
+ 使用 [CreateQueue](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-sqs-2012-11-05.html#createqueue) 创建长轮询队列。

适用于 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) 中所述。

## 设置队列属性以启用长轮询
<a name="set-attributes-on-a-queue-to-enable-long-polling"></a>

 **导入**。

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

use Aws\Exception\AwsException;
use Aws\Sqs\SqsClient;
```

 **示例代码** 

```
$queueUrl = "QUEUE_URL";

$client = new SqsClient([
    'profile' => 'default',
    'region' => 'us-west-2',
    'version' => '2012-11-05'
]);

try {
    $result = $client->setQueueAttributes([
        'Attributes' => [
            'ReceiveMessageWaitTimeSeconds' => 20
        ],
        'QueueUrl' => $queueUrl, // REQUIRED
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    error_log($e->getMessage());
}
```

## 使用长轮询检索消息
<a name="retrieve-messages-with-long-polling"></a>

 **导入**。

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

use Aws\Exception\AwsException;
use Aws\Sqs\SqsClient;
```

 **示例代码** 

```
$queueUrl = "QUEUE_URL";

$client = new SqsClient([
    'profile' => 'default',
    'region' => 'us-west-2',
    'version' => '2012-11-05'
]);

try {
    $result = $client->receiveMessage([
        'AttributeNames' => ['SentTimestamp'],
        'MaxNumberOfMessages' => 1,
        'MessageAttributeNames' => ['All'],
        'QueueUrl' => $queueUrl, // REQUIRED
        'WaitTimeSeconds' => 20,
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    error_log($e->getMessage());
}
```

## 使用长轮询创建队列
<a name="create-a-queue-with-long-polling"></a>

 **导入**。

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

use Aws\Exception\AwsException;
use Aws\Sqs\SqsClient;
```

 **示例代码** 

```
$queueName = "QUEUE_NAME";


$client = new SqsClient([
    'profile' => 'default',
    'region' => 'us-west-2',
    'version' => '2012-11-05'
]);

try {
    $result = $client->createQueue([
        'QueueName' => $queueName,
        'Attributes' => [
            'ReceiveMessageWaitTimeSeconds' => 20
        ],
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    error_log($e->getMessage());
}
```

# 在使用 适用于 PHP 的 AWS SDK 版本 3 的 Amazon SQS 中管理可见性超时
<a name="sqs-examples-managing-visibility-timeout"></a>

可见性超时是 Amazon SQS 阻止其他使用组件接收并处理消息的一段时间。要了解更多信息，请参阅[可见性超时](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-visibility-timeout.html)。

以下示例演示如何：
+ 使用 [ChangeMessageVisibilityBatch](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-sqs-2012-11-05.html#changemessagevisibilitybatch) 将队列中指定消息的可见性超时更改为新值。

适用于 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) 中所述。

## 更改多条消息的可见性超时
<a name="change-the-visibility-timeout-of-multiple-messages"></a>

 **导入**。

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

use Aws\Exception\AwsException;
use Aws\Sqs\SqsClient;
```

 **示例代码** 

```
$queueUrl = "QUEUE_URL";

$client = new SqsClient([
    'profile' => 'default',
    'region' => 'us-west-2',
    'version' => '2012-11-05'
]);

try {
    $result = $client->receiveMessage(array(
        'AttributeNames' => ['SentTimestamp'],
        'MaxNumberOfMessages' => 10,
        'MessageAttributeNames' => ['All'],
        'QueueUrl' => $queueUrl, // REQUIRED
    ));
    $messages = $result->get('Messages');
    if ($messages != null) {
        $entries = array();
        for ($i = 0; $i < count($messages); $i++) {
            $entries[] = [
                'Id' => 'unique_is_msg' . $i, // REQUIRED
                'ReceiptHandle' => $messages[$i]['ReceiptHandle'], // REQUIRED
                'VisibilityTimeout' => 3600
            ];
        }
        $result = $client->changeMessageVisibilityBatch([
            'Entries' => $entries,
            'QueueUrl' => $queueUrl
        ]);

        var_dump($result);
    } else {
        echo "No messages in queue \n";
    }
} catch (AwsException $e) {
    // output error message if fails
    error_log($e->getMessage());
}
```

# 在使用 适用于 PHP 的 AWS SDK 版本 3 的 Amazon SQS 中发送和接收消息
<a name="sqs-examples-send-receive-messages"></a>

要了解 Amazon SQS 消息，请参阅 Service Quotas 用户指南中的[向 SQS 队列发送消息](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-send-message.html)和[从 SQS 队列接收和删除消息](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-receive-delete-message.html.html)。

以下示例演示如何：
+ 使用 [SendMessage](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-sqs-2012-11-05.html#sendmessage) 向指定的队列传输消息。
+ 使用 [ReceiveMessage](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-sqs-2012-11-05.html#receivemessage) 从指定的队列检索一条或多条消息（最多 10 条）。
+ 使用 [DeleteMessage](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-sqs-2012-11-05.html#deletemessage) 从队列中删除消息。

适用于 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) 中所述。

## 发送消息
<a name="send-a-message"></a>

 **导入**。

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

use Aws\Exception\AwsException;
use Aws\Sqs\SqsClient;
```

 **示例代码** 

```
$client = new SqsClient([
    'profile' => 'default',
    'region' => 'us-west-2',
    'version' => '2012-11-05'
]);

$params = [
    'DelaySeconds' => 10,
    'MessageAttributes' => [
        "Title" => [
            'DataType' => "String",
            'StringValue' => "The Hitchhiker's Guide to the Galaxy"
        ],
        "Author" => [
            'DataType' => "String",
            'StringValue' => "Douglas Adams."
        ],
        "WeeksOn" => [
            'DataType' => "Number",
            'StringValue' => "6"
        ]
    ],
    'MessageBody' => "Information about current NY Times fiction bestseller for week of 12/11/2016.",
    'QueueUrl' => 'QUEUE_URL'
];

try {
    $result = $client->sendMessage($params);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    error_log($e->getMessage());
}
```

## 接收和删除消息
<a name="receive-and-delete-messages"></a>

 **导入**。

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

use Aws\Exception\AwsException;
use Aws\Sqs\SqsClient;
```

 **示例代码** 

```
$queueUrl = "QUEUE_URL";

$client = new SqsClient([
    'profile' => 'default',
    'region' => 'us-west-2',
    'version' => '2012-11-05'
]);

try {
    $result = $client->receiveMessage([
        'AttributeNames' => ['SentTimestamp'],
        'MaxNumberOfMessages' => 1,
        'MessageAttributeNames' => ['All'],
        'QueueUrl' => $queueUrl, // REQUIRED
        'WaitTimeSeconds' => 0,
    ]);
    if (!empty($result->get('Messages'))) {
        var_dump($result->get('Messages')[0]);
        $result = $client->deleteMessage([
            'QueueUrl' => $queueUrl, // REQUIRED
            'ReceiptHandle' => $result->get('Messages')[0]['ReceiptHandle'] // REQUIRED
        ]);
    } else {
        echo "No messages in queue. \n";
    }
} catch (AwsException $e) {
    // output error message if fails
    error_log($e->getMessage());
}
```

# 在使用 适用于 PHP 的 AWS SDK 版本 3 的 Amazon SQS 中使用死信队列
<a name="sqs-examples-dead-letter-queues"></a>

其他（源）队列可将无法成功处理的消息转到死信队列。您可以在死信队列中留出和隔离这些消息以确定其处理失败的原因。您必须单独配置将消息发送到死信队列的每个源队列。多个队列可将一个死信队列作为目标。

要了解更多信息，请参阅[使用 SQS 死信队列](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-dead-letter-queues.html)。

以下示例演示如何：
+ 使用 [SetQueueAttributes](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-sqs-2012-11-05.html#setqueueattributes) 启用死信队列。

适用于 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) 中所述。

## 启用死信队列
<a name="enable-a-dead-letter-queue"></a>

 **导入**。

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

use Aws\Exception\AwsException;
use Aws\Sqs\SqsClient;
```

 **示例代码** 

```
$queueUrl = "QUEUE_URL";

$client = new SqsClient([
    'profile' => 'default',
    'region' => 'us-west-2',
    'version' => '2012-11-05'
]);

try {
    $result = $client->setQueueAttributes([
        'Attributes' => [
            'RedrivePolicy' => "{\"deadLetterTargetArn\":\"DEAD_LETTER_QUEUE_ARN\",\"maxReceiveCount\":\"10\"}"
        ],
        'QueueUrl' => $queueUrl // REQUIRED
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    error_log($e->getMessage());
}
```

# 在使用 适用于 PHP 的 AWS SDK 版本 3 的 Amazon SQS 中使用队列
<a name="sqs-examples-using-queues"></a>

要了解有关 Amazon SQS 队列的更多信息，请参阅 [SQS 队列的工作原理](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-how-it-works.html)。

以下示例演示如何：
+ 使用 [ListQueues](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-sqs-2012-11-05.html#listqueues) 返回队列的列表。
+ 使用 [CreateQueue](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-sqs-2012-11-05.html#createqueue) 创建新队列。
+ 使用 [GetQueueUrl](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-sqs-2012-11-05.html#getqueueurl) 返回现有队列的 URL。
+ 使用 [DeleteQueue](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-sqs-2012-11-05.html#deletequeue) 删除指定的队列。

适用于 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) 中所述。

## 返回队列列表
<a name="return-a-list-of-queues"></a>

 **导入**。

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

use Aws\Exception\AwsException;
use Aws\Sqs\SqsClient;
```

 **示例代码** 

```
$client = new SqsClient([
    'profile' => 'default',
    'region' => 'us-west-2',
    'version' => '2012-11-05'
]);

try {
    $result = $client->listQueues();
    foreach ($result->get('QueueUrls') as $queueUrl) {
        echo "$queueUrl\n";
    }
} catch (AwsException $e) {
    // output error message if fails
    error_log($e->getMessage());
}
```

## 创建队列
<a name="create-a-queue"></a>

 **导入**。

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

use Aws\Exception\AwsException;
use Aws\Sqs\SqsClient;
```

 **示例代码** 

```
$queueName = "SQS_QUEUE_NAME";

$client = new SqsClient([
    'profile' => 'default',
    'region' => 'us-west-2',
    'version' => '2012-11-05'
]);

try {
    $result = $client->createQueue([
        'QueueName' => $queueName,
        'Attributes' => [
            'DelaySeconds' => 5,
            'MaximumMessageSize' => 4096, // 4 KB
        ],
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    error_log($e->getMessage());
}
```

## 返回队列的 URL
<a name="return-the-url-of-a-queue"></a>

 **导入**。

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

use Aws\Exception\AwsException;
use Aws\Sqs\SqsClient;
```

 **示例代码** 

```
$queueName = "SQS_QUEUE_NAME";

$client = new SqsClient([
    'profile' => 'default',
    'region' => 'us-west-2',
    'version' => '2012-11-05'
]);

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

## 删除队列
<a name="delete-a-queue"></a>

 **导入**。

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

use Aws\Exception\AwsException;
use Aws\Sqs\SqsClient;
```

 **示例代码** 

```
$queueUrl = "SQS_QUEUE_URL";

$client = new SqsClient([
    'profile' => 'default',
    'region' => 'us-west-2',
    'version' => '2012-11-05'
]);

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

# 使用 适用于 PHP 的 AWS SDK 版本 3 向 Amazon EventBridge 全球终端节点发送事件
<a name="eventbridge-examples"></a>

您可以使用 [Amazon EventBridge 全球终端节点](https://docs.aws.amazon.com//eventbridge/latest/userguide/eb-global-endpoints.html)来提高事件驱动型应用程序的可用性和可靠性。

[设置 EventBridge ](https://docs.aws.amazon.com//eventbridge/latest/userguide/eb-global-endpoints.html#eb-ge-create-endpoint)全局端点后，您可以使用适用于 PHP 的 SDK 向其发送事件。

**重要**  
要在适用于 PHP 的 SDK 中使用 EventBridge 全局端点，您的 PHP 环境必须安装[AWS 通用运行时 (AWS CRT) 扩展](guide_crt.md)。

以下示例使用的[PutEvents](https://docs.aws.amazon.com//aws-sdk-php/v3/api/api-eventbridge-2015-10-07.html#putevents)方法将单个事件发送`EventBridgeClient`到 EventBridge 全局终端节点。

```
<?php
/* Send a single event to an existing Amazon EventBridge global endpoint. */
require '../vendor/autoload.php';

use Aws\EventBridge\EventBridgeClient;

$evClient = new EventBridgeClient([
    'region' => 'us-east-1'
]);

$endpointId = 'xxxx123456.xxx';  // Existing EventBridge global endpointId.
$eventBusName = 'default';       // Existing event bus in the us-east-1 Region.

$event =  [
    'Source' => 'my-php-app',
    'DetailType' => 'test',
    'Detail' => json_encode(['foo' => 'bar']),
    'Time' => new DateTime(),
    'Resources' => ['php-script'],
    'EventBusName' => $eventBusName,
    'TraceHeader' => 'test'
];

$result = $evClient->putEvents([
    'EndpointId' => $endpointId,
    'Entries' => [$event]
]);
```

[这篇博文](https://aws.amazon.com/blogs//compute/introducing-global-endpoints-for-amazon-eventbridge/)包含有关 EventBridge 全局端点的更多信息。