

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# 具有 指引的程式碼範例 適用於 PHP 的 AWS SDK
<a name="examples_index"></a>

本節包含程式碼範例，示範使用 的常見 AWS 案例 適用於 PHP 的 AWS SDK。

您可以在 GitHub 上 適用於 PHP 的 AWS SDK 取得 的所有範例程式碼。 [ GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code)

## 登入資料
<a name="examplecredentials"></a>

在執行範例程式碼之前，請先設定您的 AWS 登入資料，如中所述[AWS 使用第 3 適用於 PHP 的 AWS SDK 版向 驗證](credentials.md)。然後匯入 適用於 PHP 的 AWS SDK，如 中所述[安裝第 3 適用於 PHP 的 AWS SDK 版](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)

# 使用第 3 適用於 PHP 的 AWS SDK 版的 Amazon CloudFront 範例
<a name="cf-examples"></a>

Amazon CloudFront 是一種 AWS Web 服務，可加速從您自己的 Web 伺服器或 AWS 伺服器提供靜態和動態 Web 內容，例如 Amazon S3。CloudFront 透過稱為節點的資料中心全球網路提供內容。當使用者請求您使用 CloudFront 分發的內容時，它們會路由到提供最低延遲的節點。如果內容尚未快取，CloudFront 會從原始伺服器擷取複本、提供複本，然後快取以供未來請求使用。

如需 CloudFront 的詳細資訊，請參閱[《Amazon CloudFront 開發人員指南》](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/)。

第 3 適用於 PHP 的 AWS SDK 版的所有範例程式碼都可在 [ GitHub 上取得](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code)。

# 使用 Amazon CloudFront CloudFront 分佈 適用於 PHP 的 AWS SDK
<a name="cloudfront-example-distribution"></a>

Amazon CloudFront 會在全球節點快取內容，以加速靜態和動態檔案的分佈，而這些檔案會存放在您自己的伺服器上，或在 Amazon S3 和 Amazon EC2 等 Amazon 服務上。當使用者從您的網站請求內容時，如果檔案快取到該處，CloudFront 會從最接近的節點提供內容。否則CloudFront 會擷取檔案的副本、提供該檔案，然後快取該檔案以供下一個請求使用。在節點上快取內容會降低在該區域類似使用者請求的延遲。

對於您建立的每個 CloudFront 分發，您可以指定內容所在的位置，以及在使用者提出請求時如何分發內容。這個主題著重於靜態和動態檔案 (例如 HTML、CSS、JSON 和映像檔案) 的分佈。F 或有關隨需視訊使用 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) 刪除分佈。

您可以在 GitHub 適用於 PHP 的 AWS SDK 上取得 的所有範例程式碼。 [ GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code)

## 登入資料
<a name="examplecredentials"></a>

執行範例程式碼之前，請先設定您的 AWS 登入資料，如中所述[AWS 使用第 3 適用於 PHP 的 AWS SDK 版向 驗證](credentials.md)。然後匯入 適用於 PHP 的 AWS SDK，如 中所述[安裝第 3 適用於 PHP 的 AWS SDK 版](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();
```

# 使用 Amazon CloudFront CloudFront 無效 適用於 PHP 的 AWS SDK
<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) 列出分佈。

您可以在 GitHub 上 適用於 PHP 的 AWS SDK 取得 的所有範例程式碼。 [ GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code)

## 登入資料
<a name="examplecredentials"></a>

在執行範例程式碼之前，請先設定您的 AWS 登入資料，如中所述[AWS 使用第 3 適用於 PHP 的 AWS SDK 版向 驗證](credentials.md)。然後匯入 適用於 PHP 的 AWS SDK，如 中所述[安裝第 3 適用於 PHP 的 AWS SDK 版](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();
```

# 使用第 3 適用於 PHP 的 AWS SDK 版簽署 Amazon CloudFront URLs
<a name="cloudfront-example-signed-url"></a>

已簽章 URL 可讓您提供使用者存取您的私有內容。已簽署的 URL 包含附加資訊 (例如過期時間)，以便您更有效地控制對內容的存取。此附加資訊顯示在政策聲明中，該政策聲明基於標準政策或自訂政策。如需有關如何設定私有分佈以及為什麼您需要簽署 URLs的資訊，請參閱《[Amazon CloudFront 開發人員指南》中的透過 Amazon CloudFront 提供私有內容](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/PrivateContent.html)。 Amazon CloudFront 
+ 使用 [getSignedURL](https://docs.aws.amazon.com/aws-sdk-php/v3/api/class-Aws.CloudFront.CloudFrontClient.html#_getSignedUrl) 建立已簽署的 Amazon CloudFront URL。
+ 使用 [getSignedCookie](https://docs.aws.amazon.com/aws-sdk-php/v3/api/class-Aws.CloudFront.CloudFrontClient.html#_getSignedCookie) 建立已簽署的 Amazon CloudFront cookie。

您可以在 GitHub 上 適用於 PHP 的 AWS SDK 取得 的所有範例程式碼。 [ GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code)

## 憑證
<a name="examplecredentials"></a>

在執行範例程式碼之前，請先設定您的 AWS 登入資料，如中所述[AWS 使用第 3 適用於 PHP 的 AWS SDK 版向 驗證](credentials.md)。然後匯入 適用於 PHP 的 AWS SDK，如 中所述[安裝第 3 適用於 PHP 的 AWS SDK 版](getting-started_installation.md)。

如需使用 Amazon CloudFront 的詳細資訊，請參閱 [Amazon 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 簽章的 URL
<a name="use-a-cf-signed-url"></a>

簽署 URL 的形式各有不同，取決於您要簽署的 URL 是使用「HTTP」還是「RTMP」機制。如果是「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>

做為已簽章的 URL 替代方案，您還可以授予用戶端透過已簽章的 cookie 存取私有分發權限。已簽章的 cookie 可讓您提供對多個限制檔案的存取，例如 HLS 格式視訊的所有檔案或網站中訂閱者區域的所有檔案。如需為何您可能想要使用已簽章的 Cookie 而非已簽章URLs 的詳細資訊 （反之亦然），請參閱《Amazon CloudFront 開發人員指南》中的[選擇已簽章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`，您可以透過自訂政策簽署 cookie 以提供 `'policy'` 參數，而非 `expires` 參數與 `url` 參數。自訂政策可以包含在資源金鑰中的萬用字元。這可讓您建立多個檔案的單一簽章 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();
```

## 將 CloudFront Cookie 傳送至 Guzzle 用戶端
<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');
```

如需詳細資訊，請參閱《Amazon CloudFront 開發人員指南》中的[使用已簽章的 Cookie](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/private-content-signed-cookies.html)。

# 使用第 3 適用於 PHP 的 AWS SDK 版簽署自訂 Amazon CloudSearch 網域請求
<a name="service_cloudsearch-custom-requests"></a>

Amazon CloudSearch 網域請求可以自訂超過 支援的請求 適用於 PHP 的 AWS SDK。如果您需要對受 IAM 身分驗證保護的網域提出自訂請求，您可以使用 SDK 的憑證提供者和簽署者來簽署任何 [PSR-7 請求](https://docs.aws.amazon.com/aws-sdk-php/v3/api/class-Psr.Http.Message.RequestInterface.html)。

例如，您若依照 [CloudSearch 入門指南](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 簽署通訊協定簽署請求。

您可以在 GitHub 上 適用於 PHP 的 AWS SDK 取得 的所有範例程式碼。 [ GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code)

## 登入資料
<a name="examplecredentials"></a>

在執行範例程式碼之前，請先設定您的 AWS 登入資料，如中所述[AWS 使用第 3 適用於 PHP 的 AWS SDK 版向 驗證](credentials.md)。然後匯入 適用於 PHP 的 AWS SDK，如 中所述[安裝第 3 適用於 PHP 的 AWS SDK 版](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();
```

# 使用第 3 適用於 PHP 的 AWS SDK 版的 Amazon CloudWatch 範例
<a name="cw-examples"></a>

Amazon CloudWatch (CloudWatch) 是一種 Web 服務， AWS 可即時監控您的 Amazon Web Services 資源和您在其上執行的應用程式。您可以使用 CloudWatch 收集和追蹤指標，這些是您可以為您的資源和應用程式測量的變數。CloudWatch 警示會根據您定義的規則，傳送通知或自動變更您要監控的資源。

您可以在 GitHub 上 適用於 PHP 的 AWS SDK 取得 的所有範例程式碼。 [ GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code)

## 登入資料
<a name="examplecredentials"></a>

在執行範例程式碼之前，請先設定您的 AWS 登入資料，如中所述[AWS 使用第 3 適用於 PHP 的 AWS SDK 版向 驗證](credentials.md)。然後匯入 適用於 PHP 的 AWS SDK，如 中所述[安裝第 3 適用於 PHP 的 AWS SDK 版](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)

# 使用第 3 適用於 PHP 的 AWS SDK 版的 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) 刪除警示。

您可以在 GitHub 上 適用於 PHP 的 AWS SDK 取得 的所有範例程式碼。 [ GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code)

## 登入資料
<a name="examplecredentials"></a>

在執行範例程式碼之前，請先設定您的 AWS 登入資料，如中所述[AWS 使用第 3 適用於 PHP 的 AWS SDK 版向 驗證](credentials.md)。然後匯入 適用於 PHP 的 AWS SDK，如 中所述[安裝第 3 適用於 PHP 的 AWS SDK 版](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();
```

# 使用第 3 適用於 PHP 的 AWS SDK 版從 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) 取得指定指標的統計資料。

您可以在 GitHub 適用於 PHP 的 AWS SDK 上取得 的所有範例程式碼。 [ GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code)

## 登入資料
<a name="examplecredentials"></a>

在執行範例程式碼之前，請先設定您的 AWS 登入資料，如中所述[AWS 使用第 3 適用於 PHP 的 AWS SDK 版向 驗證](credentials.md)。然後匯入 適用於 PHP 的 AWS SDK，如 中所述[安裝第 3 適用於 PHP 的 AWS SDK 版](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();
```

# 使用第 3 適用於 PHP 的 AWS SDK 版在 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) 建立警示。

您可以在 GitHub 上 適用於 PHP 的 AWS SDK 取得 的所有範例程式碼。 [ GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code)

## 登入資料
<a name="examplecredentials"></a>

在執行範例程式碼之前，請先設定您的 AWS 登入資料，如中所述[AWS 使用第 3 適用於 PHP 的 AWS SDK 版向 驗證](credentials.md)。然後匯入 適用於 PHP 的 AWS SDK，如 中所述[安裝第 3 適用於 PHP 的 AWS SDK 版](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();
```

# 使用第 3 適用於 PHP 的 AWS SDK 版將事件傳送至 Amazon CloudWatch Events
<a name="cw-examples-sending-events"></a>

CloudWatch Events 提供近乎即時的系統事件串流，將 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) 在規則中加入目標。
+ 使用 [PutEvents](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-events-2015-10-07.html#putevents) 將自訂事件傳送至 CloudWatch Events。

您可以在 GitHub 上 適用於 PHP 的 AWS SDK 取得 的所有範例程式碼。 [ GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code)

## 憑證
<a name="examplecredentials"></a>

在執行範例程式碼之前，請先設定您的 AWS 登入資料，如中所述[AWS 使用第 3 適用於 PHP 的 AWS SDK 版向 驗證](credentials.md)。然後匯入 適用於 PHP 的 AWS SDK，如 中所述[安裝第 3 適用於 PHP 的 AWS SDK 版](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());
}
```

# 使用警示動作搭配 Amazon CloudWatch 警示搭配第 3 適用於 PHP 的 AWS SDK 版
<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) 對指定的警示停用動作。

您可以在 GitHub 上 適用於 PHP 的 AWS SDK 取得 的所有範例程式碼。 [ GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code)

## 登入資料
<a name="examplecredentials"></a>

在執行範例程式碼之前，請先設定您的 AWS 登入資料，如中所述[AWS 使用第 3 適用於 PHP 的 AWS SDK 版向 驗證](credentials.md)。然後匯入 適用於 PHP 的 AWS SDK，如 中所述[安裝第 3 適用於 PHP 的 AWS SDK 版](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();
```

# 使用第 3 適用於 PHP 的 AWS SDK 版的 Amazon EC2 範例
<a name="ec2-examples"></a>

Amazon Elastic Compute Cloud (Amazon EC2) 是一種 Web 服務，可在雲端提供虛擬伺服器託管。它旨在透過提供可調整大小的運算容量，讓開發人員更輕鬆地進行 Web 規模雲端運算。

您可以在 GitHub 上 適用於 PHP 的 AWS SDK 取得 的所有範例程式碼。 [ GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code)

## 登入資料
<a name="examplecredentials"></a>

在執行範例程式碼之前，請先設定您的 AWS 登入資料，如中所述[AWS 使用第 3 適用於 PHP 的 AWS SDK 版向 驗證](credentials.md)。然後匯入 適用於 PHP 的 AWS SDK，如 中所述[安裝第 3 適用於 PHP 的 AWS SDK 版](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)

# 使用第 3 適用於 PHP 的 AWS SDK 版管理 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 後端 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) 請求重新啟動一個或多個執行個體。

您可以在 GitHub 上 適用於 PHP 的 AWS SDK 取得 的所有範例程式碼。 [ GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code)

## 登入資料
<a name="examplecredentials"></a>

在執行範例程式碼之前，請先設定您的 AWS 登入資料，如中所述[AWS 使用第 3 適用於 PHP 的 AWS SDK 版向 驗證](credentials.md)。然後匯入 適用於 PHP 的 AWS SDK，如 中所述[安裝第 3 適用於 PHP 的 AWS SDK 版](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);
```

# 搭配 Amazon EC2 與第 3 適用於 PHP 的 AWS SDK 版使用彈性 IP 地址
<a name="ec2-examples-using-elastic-ip-addresses"></a>

彈性 IP 地址是針對動態雲端運算設計的靜態 IP 地址。彈性 IP 地址與您的 相關聯 AWS 帳戶。這是一個公有 IP 地址，可從網際網路存取。如果您的執行個體沒有公有 IP 地址，可以將彈性 IP 地址與執行個體建立關聯，來啟用與網際網路通訊的功能。

下列範例示範如何：
+ 使用 [DescribeInstances](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-ec2-2016-11-15.html#describeinstances) 描述一個或多個執行個體。
+ 使用 [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) 發佈彈性 IP 地址。

您可以在 GitHub 上 適用於 PHP 的 AWS SDK 取得 的所有範例程式碼。 [ GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code)

## 憑證
<a name="examplecredentials"></a>

在執行範例程式碼之前，請先設定您的 AWS 登入資料，如中所述[AWS 使用第 3 適用於 PHP 的 AWS SDK 版向 驗證](credentials.md)。然後匯入 適用於 PHP 的 AWS SDK，如 中所述[安裝第 3 適用於 PHP 的 AWS SDK 版](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);
```

# 搭配第 3 適用於 PHP 的 AWS SDK 版使用 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 的區域。

您可以在 GitHub 上 適用於 PHP 的 AWS SDK 取得 的所有範例程式碼。 [ GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code)

## 登入資料
<a name="examplecredentials"></a>

在執行範例程式碼之前，請先設定您的 AWS 登入資料，如中所述[AWS 使用第 3 適用於 PHP 的 AWS SDK 版向 驗證](credentials.md)。然後匯入 適用於 PHP 的 AWS SDK，如 中所述[安裝第 3 適用於 PHP 的 AWS SDK 版](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);
```

# 使用第 3 適用於 PHP 的 AWS SDK 版的 Amazon EC2 金鑰對
<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) 描述一個或多個金鑰對。

您可以在 GitHub 上 適用於 PHP 的 AWS SDK 取得 的所有範例程式碼。 [ GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code)

## 登入資料
<a name="examplecredentials"></a>

在執行範例程式碼之前，請先設定您的 AWS 登入資料，如中所述[AWS 使用第 3 適用於 PHP 的 AWS SDK 版向 驗證](credentials.md)。然後匯入 適用於 PHP 的 AWS SDK，如 中所述[安裝第 3 適用於 PHP 的 AWS SDK 版](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);
```

# 使用第 3 適用於 PHP 的 AWS SDK 版在 Amazon EC2 中使用安全群組
<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) 刪除安全群組。

您可以在 GitHub 上 適用於 PHP 的 AWS SDK 取得 的所有範例程式碼。 [ GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code)

## 登入資料
<a name="examplecredentials"></a>

在執行範例程式碼之前，請先設定您的 AWS 登入資料，如中所述[AWS 使用第 3 適用於 PHP 的 AWS SDK 版向 驗證](credentials.md)。然後匯入 適用於 PHP 的 AWS SDK，如 中所述[安裝第 3 適用於 PHP 的 AWS SDK 版](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);
```

# 使用第 3 適用於 PHP 的 AWS SDK 版簽署 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 用戶端支援請求簽署，但如果您使用的用戶端不是 ，您可以使用 的內建憑證提供者和簽署者簽署任意 PSR-7 請求 適用於 PHP 的 AWS SDK。

下列範例示範如何：
+ 使用 [SignatureV4](https://docs.aws.amazon.com/aws-sdk-php/v3/api/class-Aws.Signature.SignatureV4.html#_signRequest) 使用 AWS 簽署通訊協定簽署請求。

您可以在 GitHub 上 適用於 PHP 的 AWS SDK 取得 的所有範例程式碼。 [ GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code)

## 登入資料
<a name="examplecredentials"></a>

在執行範例程式碼之前，請先設定您的 AWS 登入資料，如中所述[AWS 使用第 3 適用於 PHP 的 AWS SDK 版向 驗證](credentials.md)。然後匯入 適用於 PHP 的 AWS SDK，如 中所述[安裝第 3 適用於 PHP 的 AWS SDK 版](getting-started_installation.md)。

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

OpenSearch Service 使用 [Signature 第 4 版](https://docs.aws.amazon.com/general/latest/gr/signature-version-4.html)。這表示您需要針對服務的簽署名稱 （在此案例中`es`為 ) 和 OpenSearch Service 網域 AWS 的區域簽署請求。您可以在 的區域和端點頁面上找到 OpenSearch Service 支援的區域完整清單 Amazon Web Services 一般參考。 [AWS](https://docs.aws.amazon.com/general/latest/gr/rande.html)不過，在此範例中，我們會針對`us-west-2`區域中的 OpenSearch Service 網域簽署請求。

您需要提供登入資料，您可以使用 SDK 的預設提供者鏈結或第 [3 適用於 PHP 的 AWS SDK 版登入資料中所述的任何形式的登入資料](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);
```

# AWS Identity and Access Management 使用第 3 適用於 PHP 的 AWS SDK 版的範例
<a name="iam-examples"></a>

AWS Identity and Access Management (IAM) 是一種 Web 服務，可讓 Amazon Web Services 客戶管理 中的使用者和使用者許可 AWS。此服務以雲端中有多個使用者或系統使用 AWS 產品的組織為目標。透過 IAM，您可以集中管理使用者、存取金鑰等安全登入資料，以及控制使用者可以存取哪些 AWS 資源的許可。

您可以在 GitHub 上 適用於 PHP 的 AWS SDK 取得 的所有範例程式碼。 [ GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code)

## 登入資料
<a name="examplecredentials"></a>

在執行範例程式碼之前，請先設定您的 AWS 登入資料，如中所述[AWS 使用第 3 適用於 PHP 的 AWS SDK 版向 驗證](credentials.md)。然後匯入 適用於 PHP 的 AWS SDK，如 中所述[安裝第 3 適用於 PHP 的 AWS SDK 版](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)

# 使用第 3 適用於 PHP 的 AWS SDK 版管理 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 使用者相關聯的存取金鑰 IDs 的相關資訊。
+ 使用 [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) 將存取金鑰的狀態從「作用中」變更為「非作用中」(或相反)。
+ 使用 [DeleteAccessKey](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-iam-2010-05-08.html#deleteaccesskey) 刪除與 IAM 使用者相關聯的存取金鑰對。

您可以在 GitHub 上 適用於 PHP 的 AWS SDK 取得 的所有範例程式碼。 [ GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code)

## 登入資料
<a name="examplecredentials"></a>

在執行範例程式碼之前，請先設定您的 AWS 登入資料，如中所述[AWS 使用第 3 適用於 PHP 的 AWS SDK 版向 驗證](credentials.md)。然後匯入 適用於 PHP 的 AWS SDK，如 中所述[安裝第 3 適用於 PHP 的 AWS SDK 版](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());
}
```

# 使用第 3 適用於 PHP 的 AWS SDK 版管理 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 使用者。

您可以在 GitHub 上 適用於 PHP 的 AWS SDK 取得 的所有範例程式碼。 [ GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code)

## 登入資料
<a name="examplecredentials"></a>

在執行範例程式碼之前，請先設定您的 AWS 登入資料，如中所述[AWS 使用第 3 適用於 PHP 的 AWS SDK 版向 驗證](credentials.md)。然後匯入 適用於 PHP 的 AWS SDK，如 中所述[安裝第 3 適用於 PHP 的 AWS SDK 版](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());
}
```

# 搭配第 3 適用於 PHP 的 AWS SDK 版使用 IAM 帳戶別名
<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) 建立別名。
+  AWS 帳戶 使用 [ListAccountAliases](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-iam-2010-05-08.html#listaccountaliases) 列出與 相關聯的別名。
+ 使用 [DeleteAccountAlias](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-iam-2010-05-08.html#deleteaccountalias) 刪除別名。

您可以在 GitHub 上 適用於 PHP 的 AWS SDK 取得 的所有範例程式碼。 [ GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code)

## 登入資料
<a name="examplecredentials"></a>

在執行範例程式碼之前，請先設定您的 AWS 登入資料，如中所述[AWS 使用第 3 適用於 PHP 的 AWS SDK 版向 驗證](credentials.md)。然後匯入 適用於 PHP 的 AWS SDK，如 中所述[安裝第 3 適用於 PHP 的 AWS SDK 版](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());
}
```

# 使用第 3 適用於 PHP 的 AWS SDK 版的 IAM 政策
<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) 刪除群組政策。

您可以在 GitHub 適用於 PHP 的 AWS SDK 上取得 的所有範例程式碼。 [ GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code)

## 登入資料
<a name="examplecredentials"></a>

執行範例程式碼之前，請先設定您的 AWS 登入資料，如中所述[AWS 使用第 3 適用於 PHP 的 AWS SDK 版向 驗證](credentials.md)。然後匯入 適用於 PHP 的 AWS SDK，如 中所述[安裝第 3 適用於 PHP 的 AWS SDK 版](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());
}
```

# 使用第 3 適用於 PHP 的 AWS SDK 版的 IAM 伺服器憑證
<a name="iam-examples-working-with-certs"></a>

若要啟用網站或應用程式的 HTTPS 連線 AWS，您需要 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) 刪除憑證。

您可以在 GitHub 上 適用於 PHP 的 AWS SDK 取得 的所有範例程式碼。 [ GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code)

## 登入資料
<a name="examplecredentials"></a>

在執行範例程式碼之前，請先設定您的 AWS 登入資料，如中所述[AWS 使用第 3 適用於 PHP 的 AWS SDK 版向 驗證](credentials.md)。然後匯入 適用於 PHP 的 AWS SDK，如 中所述[安裝第 3 適用於 PHP 的 AWS SDK 版](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());
}
```

# AWS Key Management Service 使用第 3 適用於 PHP 的 AWS SDK 版的範例
<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 可協助您維持對誰可以使用您的金鑰的控制權，並存取您的加密資料。

第 3 適用於 PHP 的 AWS SDK 版的所有範例程式碼都可在 [ GitHub 上取得](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code)。

**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 和 第 3 適用於 PHP 的 AWS SDK 版使用金鑰
<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 金鑰來加密您的資料。

下列範例示範如何：
+ 使用 [CreateKey](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-kms-2014-11-01.html#createkey) 建立客戶 KMS 金鑰。
+ 使用 [GenerateDataKey](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-kms-2014-11-01.html#generatedatakey) 產生資料金鑰。
+ 使用 [DescribeKey](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-kms-2014-11-01.html#describekey) 檢視 KMS 金鑰。
+ 使用 [ListKeys](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-kms-2014-11-01.html#listkeys) 取得 KMS 金鑰的金鑰 IDs 和金鑰 ARNS。
+ 使用 [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) 停用 KMS 金鑰。

您可以在 GitHub 上 適用於 PHP 的 AWS SDK 取得 的所有範例程式碼。 [ GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code)

## 憑證
<a name="examplecredentials"></a>

在執行範例程式碼之前，請先設定您的 AWS 登入資料，如中所述[AWS 使用第 3 適用於 PHP 的 AWS SDK 版向 驗證](credentials.md)。然後匯入 適用於 PHP 的 AWS SDK，如 中所述[安裝第 3 適用於 PHP 的 AWS SDK 版](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 Resource Name (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
<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 適用於 PHP 的 AWS SDK 版加密和解密 AWS KMS 資料金鑰
<a name="kms-example-encrypt"></a>

資料金鑰是加密金鑰，您可以用來加密資料，包括大量資料和其他資料加密金鑰。

您可以使用 AWS Key Management Service的 (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 金鑰重新加密資料金鑰。

您可以在 GitHub 上 適用於 PHP 的 AWS SDK 取得 的所有範例程式碼。 [ GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code)

## 憑證
<a name="examplecredentials"></a>

在執行範例程式碼之前，請先設定您的 AWS 登入資料，如中所述[AWS 使用第 3 適用於 PHP 的 AWS SDK 版向 驗證](credentials.md)。然後匯入 適用於 PHP 的 AWS SDK，如 中所述[安裝第 3 適用於 PHP 的 AWS SDK 版](getting-started_installation.md)。

如需使用 AWS Key Management Service (AWS KMS) 的詳細資訊，請參閱 [AWS KMS 開發人員指南](https://docs.aws.amazon.com/kms/latest/developerguide/)。

## 加密
<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";
}
```

## 解密
<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) 或 [Encrypt](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) 或 [Encrypt](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";
}
```

# 使用第 3 適用於 PHP 的 AWS SDK 版使用 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) 設定金鑰政策。

您可以在 GitHub 上 適用於 PHP 的 AWS SDK 取得 的所有範例程式碼。 [ GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code)

## 憑證
<a name="examplecredentials"></a>

在執行範例程式碼之前，請先設定您的 AWS 登入資料，如中所述[AWS 使用第 3 適用於 PHP 的 AWS SDK 版向 驗證](credentials.md)。然後匯入 適用於 PHP 的 AWS SDK，如 中所述[安裝第 3 適用於 PHP 的 AWS SDK 版](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 和 第 3 適用於 PHP 的 AWS SDK 版使用授予
<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)。

下列範例示範如何：
+ 使用 [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) 淘汰 KMS 金鑰的授予。
+ 使用 RevokeGrant 撤銷 KMS [RevokeGrant](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-kms-2014-11-01.html#revokegrant)。

您可以在 GitHub 上 適用於 PHP 的 AWS SDK 取得 的所有範例程式碼。 [ GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code)

## 憑證
<a name="examplecredentials"></a>

在執行範例程式碼之前，請先設定您的 AWS 登入資料，如中所述[AWS 使用第 3 適用於 PHP 的 AWS SDK 版向 驗證](credentials.md)。然後匯入 適用於 PHP 的 AWS SDK，如 中所述[安裝第 3 適用於 PHP 的 AWS SDK 版](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 和 第 3 適用於 PHP 的 AWS SDK 版使用別名
<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) 刪除別名。

您可以在 GitHub 上 適用於 PHP 的 AWS SDK 取得 的所有範例程式碼。 [ GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code)

## 憑證
<a name="examplecredentials"></a>

在執行範例程式碼之前，請先設定您的 AWS 登入資料，如中所述[AWS 使用第 3 適用於 PHP 的 AWS SDK 版向 驗證](credentials.md)。然後匯入 適用於 PHP 的 AWS SDK，如 中所述[安裝第 3 適用於 PHP 的 AWS SDK 版](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 金鑰建立別名， 會為相同的 KMS 金鑰`CreateAlias`建立另一個別名。其並不會取代現有的別名。

 **匯入** 

```
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";
}
```

# 使用第 3 適用於 PHP 的 AWS SDK 版的 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)。

第 3 適用於 PHP 的 AWS SDK 版的所有範例程式碼都可在 [ GitHub 上取得](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code)。

**Topics**
+ [Kinesis 資料串流](kinesis-example-data-stream.md)
+ [Kinesis 碎片](kinesis-example-shard.md)
+ [Kinesis Data Firehose 交付串流](kinesis-firehose-example-delivery-stream.md)

# 使用 Kinesis Data Streams API 和第 3 適用於 PHP 的 AWS SDK 版建立資料串流
<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) 刪除資料串流。

您可以在 GitHub 上 適用於 PHP 的 AWS SDK 取得 的所有範例程式碼。 [ GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code)

## 登入資料
<a name="examplecredentials"></a>

在執行範例程式碼之前，請先設定您的 AWS 登入資料，如中所述[AWS 使用第 3 適用於 PHP 的 AWS SDK 版向 驗證](credentials.md)。然後匯入 適用於 PHP 的 AWS SDK，如 中所述[安裝第 3 適用於 PHP 的 AWS SDK 版](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 個碎片的相關資訊。請記得先`StreamStatus`檢查回應，再將資料寫入 Kinesis 資料串流。

若要擷取指定 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 區域中來自 的前 10 AWS 帳戶 個資料串流。使用傳回的 ``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 和第 3 適用於 PHP 的 AWS SDK 版管理資料碎片
<a name="kinesis-example-shard"></a>

Amazon Kinesis Data Streams 可讓您將即時資料傳送至端點。資料流程速率取決於串流中的碎片數目。

每秒寫入單個碎片的記錄可多達 1,000 筆。各碎片另有每秒 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) 增加或減少串流中的碎片數目。

您可以在 GitHub 上 適用於 PHP 的 AWS SDK 取得 的所有範例程式碼。 [ GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code)

## 登入資料
<a name="examplecredentials"></a>

在執行範例程式碼之前，請先設定您的 AWS 登入資料，如中所述[AWS 使用第 3 適用於 PHP 的 AWS SDK 版向 驗證](credentials.md)。然後匯入 適用於 PHP 的 AWS SDK，如 中所述[安裝第 3 適用於 PHP 的 AWS SDK 版](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 和 第 3 適用於 PHP 的 AWS SDK 版建立交付串流
<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) 刪除交付串流。

您可以在 GitHub 上 適用於 PHP 的 AWS SDK 取得 的所有範例程式碼。 [ GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code)

## 登入資料
<a name="examplecredentials"></a>

在執行範例程式碼之前，請先設定您的 AWS 登入資料，如中所述[AWS 使用第 3 適用於 PHP 的 AWS SDK 版向 驗證](credentials.md)。然後匯入 適用於 PHP 的 AWS SDK，如 中所述[安裝第 3 適用於 PHP 的 AWS SDK 版](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 使用第 3 適用於 PHP 的 AWS SDK 版的範例
<a name="emc-examples"></a>

AWS Elemental MediaConvert 是以檔案為基礎的影片轉碼服務，具有廣播級功能。您可以將其用於建立跨網際網路的廣播資產及隨選視訊 (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>

在此範例中，您使用第 3 適用於 PHP 的 AWS SDK 版來呼叫 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) 

您可以在 GitHub 上 適用於 PHP 的 AWS SDK 取得 的所有範例程式碼。 [ GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code)

### 憑證
<a name="examplecredentials"></a>

在執行範例程式碼之前，請先設定您的 AWS 登入資料，如中所述[AWS 使用第 3 適用於 PHP 的 AWS SDK 版向 驗證](credentials.md)。然後匯入 適用於 PHP 的 AWS SDK，如 中所述[安裝第 3 適用於 PHP 的 AWS SDK 版](getting-started_installation.md)。

若要存取 MediaConvert 用戶端，請建立可讓您 AWS Elemental MediaConvert 存取輸入檔案的 IAM 角色，以及存放輸出檔案的 Amazon S3 儲存貯體。如需詳細資訊，請參閱[《 使用者指南》中的設定 IAM 許可](https://docs.aws.amazon.com/mediaconvert/latest/ug/iam-role.html)。 [AWS Elemental MediaConvert](https://docs.aws.amazon.com/mediaconvert/latest/ug/)

### 建立用戶端
<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，包括指定以 ASCENDING 或 DESCENDING 順序排序清單的值、要檢查的任務佇列 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";
}
```

# 使用第 3 版的 Amazon S3 範例 適用於 PHP 的 AWS SDK
<a name="s3-examples"></a>

Amazon Simple Storage Service (Amazon S3) 是一種 Web 服務，可提供高度可擴展的雲端儲存。Amazon S3 提供易於使用的物件儲存，具有簡單的 Web 服務介面，可從 Web 上的任何位置儲存和擷取任意數量的資料。

您可以在 GitHub 上 適用於 PHP 的 AWS SDK 取得 的所有範例程式碼。 [ GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code)

## 憑證
<a name="examplecredentials"></a>

在執行範例程式碼之前，請先設定您的 AWS 登入資料，如中所述[AWS 使用第 3 適用於 PHP 的 AWS SDK 版向 驗證](credentials.md)。然後匯入 適用於 PHP 的 AWS SDK，如 中所述[安裝第 3 適用於 PHP 的 AWS SDK 版](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 預先簽章POSTs](s3-presigned-post.md)
+ [使用 Amazon S3 儲存貯體做為靜態 Web 主機](s3-examples-static-web-host.md)
+ [使用 Amazon S3 儲存貯體政策](s3-examples-bucket-policies.md)
+ [使用 S3 存取點 ARNs](s3-examples-access-point-arn.md)
+ [使用多區域存取點](s3-multi-region-access-points.md)

# 使用第 3 版建立和使用 Amazon S3 儲存貯體 適用於 PHP 的 AWS SDK
<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) 將物件新增到儲存貯體。

您可以在 GitHub 適用於 PHP 的 AWS SDK 上取得 的所有範例程式碼。 [ GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code)

## 登入資料
<a name="examplecredentials"></a>

執行範例程式碼之前，請先設定您的 AWS 登入資料，如中所述[AWS 使用第 3 適用於 PHP 的 AWS SDK 版向 驗證](credentials.md)。然後匯入 適用於 PHP 的 AWS SDK，如 中所述[安裝第 3 適用於 PHP 的 AWS SDK 版](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";
}
```

# 使用第 3 版管理 Amazon S3 儲存貯體存取許可 適用於 PHP 的 AWS SDK
<a name="s3-examples-access-permissions"></a>

存取控制清單 (ACL) 是可用來管理儲存貯體與物件存取的其中一個資源類型存取政策選項。您可以使用 ACLs將基本讀取/寫入許可授予其他 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 對儲存貯體設定許可。

您可以在 GitHub 上 適用於 PHP 的 AWS SDK 取得 的所有範例程式碼。 [ GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code)

## 登入資料
<a name="examplecredentials"></a>

在執行範例程式碼之前，請先設定您的 AWS 登入資料，如中所述[AWS 使用第 3 適用於 PHP 的 AWS SDK 版向 驗證](credentials.md)。然後匯入 適用於 PHP 的 AWS SDK，如 中所述[安裝第 3 適用於 PHP 的 AWS SDK 版](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";
}
```

# 使用第 3 版設定 Amazon S3 儲存貯體 適用於 PHP 的 AWS SDK
<a name="s3-examples-configuring-a-bucket"></a>

跨來源資源分享 (CORS) 會定義一種方式，讓載入單一個網域的用戶端 Web 應用程式，能與不同網域中的資源互動。透過 Amazon S3 中的 CORS 支援，您可以使用 Amazon S3 建置豐富的用戶端 Web 應用程式，並選擇性地允許跨來源存取您的 Amazon S3 資源。

如需搭配 Amazon S3 儲存貯體使用 CORS 組態的詳細資訊，請參閱[跨來源資源共用 (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 組態。

您可以在 GitHub 上 適用於 PHP 的 AWS SDK 取得 的所有範例程式碼。 [ GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code)

## 登入資料
<a name="examplecredentials"></a>

在執行範例程式碼之前，請先設定您的 AWS 登入資料，如中所述[AWS 使用第 3 適用於 PHP 的 AWS SDK 版向 驗證](credentials.md)。然後匯入 適用於 PHP 的 AWS SDK，如 中所述[安裝第 3 適用於 PHP 的 AWS SDK 版](getting-started_installation.md)。

## 取得 CORS 組態
<a name="get-the-cors-configuration"></a>

使用下列程式碼建立 PHP 檔案。首先，建立一個 AWS.S3 用戶端服務，然後呼叫 `getBucketCors` 方法，並指定具有您所需要 CORS 組態的儲存貯體。

唯一需要的參數，就是所選取儲存貯體的名稱。如果儲存貯體目前具有 CORS 組態，Amazon S3 會將該組態傳回為 [CORSRules 物件](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->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 組態的儲存貯體，然後指定 CORSConfiguration 為 [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 的物件。

下列範例將說明：
+ 使用 [ObjectUploader](https://docs.aws.amazon.com/aws-sdk-php/v3/api/class-Aws.S3.ObjectUploader.html) 將物件上傳至 Amazon S3。
+ 使用 [MultipartUploader](https://docs.aws.amazon.com/aws-sdk-php/v3/api/class-Aws.S3.MultipartUploader.html) 為 Amazon S3 物件建立分段上傳。
+ 使用 [ObjectCopier](https://docs.aws.amazon.com/aws-sdk-php/v3/api/class-Aws.S3.ObjectCopier.html) 將物件從一個 Amazon S3 位置複製到另一個位置。

您可以在 GitHub 上 適用於 PHP 的 AWS SDK 取得 的所有範例程式碼。 [ GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code)

## 憑證
<a name="examplecredentials"></a>

在執行範例程式碼之前，請先設定您的 AWS 登入資料，如中所述[AWS 使用第 3 適用於 PHP 的 AWS SDK 版向 驗證](credentials.md)。然後匯入 適用於 PHP 的 AWS SDK，如 中所述[安裝第 3 適用於 PHP 的 AWS SDK 版](getting-started_installation.md)。

## 物件上傳程式
<a name="object-uploader"></a>

如果您不確定 `PutObject`或 `MultipartUploader` 是否最適合任務，請使用 `ObjectUploader`。 會根據承載大小`MultipartUploader`，使用 `PutObject`或 將大型檔案`ObjectUploader`上傳至 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);
```

### Configuration
<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`值，軟體開發套件會叫用此回呼。如需可新增至`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`值，軟體開發套件會叫用此回呼。如需可套用至`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();
```

### Configuration
<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 stream](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";
}
```

# 使用第 3 版的 Amazon S3 預先簽章 URL 適用於 PHP 的 AWS SDK
<a name="s3-presigned-url"></a>

您可以將必要資訊當做查詢字串參數來傳遞，以驗證特定類型的要求，而不使用授權 HTTP 標頭。這有助於啟用直接第三方瀏覽器存取您的私有 Amazon S3 資料，而無需代理請求。其概念是建構「預先簽署」請求，並將其編碼為另一個使用者可以使用的 URL。此外，您可以透過指定過期時間，來限制預先簽章的要求。

## 為 HTTP GET 請求建立預先簽章的 URL
<a name="s3-presigned-url-get"></a>

下列程式碼範例示範如何使用適用於 PHP 的 開發套件，為 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;
```

方法[的 API 參考`createPresignedRequest`](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 的 開發套件，為 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;
    }
}
```

# 使用第 Amazon S3POSTs 適用於 PHP 的 AWS SDK
<a name="s3-presigned-post"></a>

與預先簽章URLs 類似，預先簽章POSTs 可讓您提供寫入存取權給使用者，而不需提供 AWS 登入資料。預先簽章的 POST 表單可以由 [AwsS3PostObjectV4](https://docs.aws.amazon.com/aws-sdk-php/v3/api/class-Aws.S3.PostObjectV4.html) 的執行個體來協助建立。

下列範例示範如何：
+ 使用 [PostObjectV4](https://docs.aws.amazon.com/aws-sdk-php/v3/api/class-Aws.S3.PostObjectV4.html) 取得 S3 物件 POST 上傳的資料。

您可以在 GitHub 上 適用於 PHP 的 AWS SDK 取得 的所有範例程式碼。 [ GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code)

## 登入資料
<a name="examplecredentials"></a>

**注意**  
`PostObjectV4` 不適用於來自 的登入資料 AWS IAM Identity Center。

在執行範例程式碼之前，請先設定您的 AWS 登入資料，如中所述[AWS 使用第 3 適用於 PHP 的 AWS SDK 版向 驗證](credentials.md)。然後匯入 適用於 PHP 的 AWS SDK，如 中所述[安裝第 3 適用於 PHP 的 AWS SDK 版](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))
+ 政策的過期時間字串 (選擇性，預設為一小時)。

 **匯入** 

```
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>
```

# 透過第 3 版使用 Amazon S3 儲存貯體做為靜態 Web 主機 適用於 PHP 的 AWS SDK
<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) 從儲存貯體移除網站組態。

第 3 適用於 PHP 的 AWS SDK 版的所有範例程式碼都可在 [ GitHub 上取得](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code)。

## 登入資料
<a name="credentials-s3-examples-static-web-host"></a>

在執行範例程式碼之前，請設定您的 AWS 登入資料。請參閱第 [3 適用於 PHP 的 AWS SDK 版的登入](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";
}
```

# 使用第 3 版的 Amazon S3 儲存貯體政策 適用於 PHP 的 AWS SDK
<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) 從儲存貯體刪除政策。

您可以在 GitHub 適用於 PHP 的 AWS SDK 上取得 的所有範例程式碼。 [ GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code)

## 登入資料
<a name="examplecredentials"></a>

在執行範例程式碼之前，請先設定您的 AWS 登入資料，如中所述[AWS 使用第 3 適用於 PHP 的 AWS SDK 版向 驗證](credentials.md)。然後匯入 適用於 PHP 的 AWS SDK，如 中所述[安裝第 3 適用於 PHP 的 AWS SDK 版](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 存取點 ARNs 第 3 適用於 PHP 的 AWS SDK 版
<a name="s3-examples-access-point-arn"></a>

S3 導入存取點，這是一種與 S3 儲存貯體互動的新方式。存取點可以套用唯一的政策和組態，而不是直接套用至儲存貯體。 適用於 PHP 的 AWS SDK 可讓您將儲存貯體欄位中ARNs 用於 API 操作，而不是明確指定儲存貯體名稱。如需 S3 存取點和 ARNs運作方式的詳細資訊，請參閱[此處](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 搭配使用，從儲存貯體擷取物件。
+ 將 [PuTOObject](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-s3-2006-03-01.html#putobject) 與存取點 ARN 搭配使用，將物件新增至儲存貯體。
+ 將 S3 用戶端設定為使用 ARN 區域，而不是用戶端區域。

您可以在 GitHub 上 適用於 PHP 的 AWS SDK 取得 的所有範例程式碼。 [ GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code)

## 登入資料
<a name="examplecredentials"></a>

在執行範例程式碼之前，請先設定您的 AWS 登入資料，如中所述[AWS 使用第 3 適用於 PHP 的 AWS SDK 版向 驗證](credentials.md)。然後匯入 適用於 PHP 的 AWS SDK，如 中所述[安裝第 3 適用於 PHP 的 AWS SDK 版](getting-started_installation.md)。

 **匯入** 

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

use Aws\S3\S3Client;
```

## 取得物件
<a name="get-object"></a>

首先建立指定 AWS 區域和版本的 AWS.S3 用戶端服務。然後使用您的金鑰和 `Bucket` 欄位中的 S3 存取點 ARN 呼叫該 `getObject` 方法，該方法將從與該存取點關聯的儲存貯體中獲取物件。

 **範例程式碼** 

```
$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` 用所需的金鑰、主體或來源檔案和 `Bucket` 欄位中的 S3 存取點 ARN 呼叫該方法，這會將物件放入與該存取點關聯的儲存貯體中。

 **範例程式碼** 

```
$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 共用組態檔案中`s3_use_arn_region`的組態變數 （預設為 )`~/.aws/config`。

```
[default]
s3_use_arn_region = true
```

# 搭配第 3 版使用 Amazon S3 多區域存取點 適用於 PHP 的 AWS SDK
<a name="s3-multi-region-access-points"></a>

[Amazon Simple Storage Service (S3) 多區域存取點](https://docs.aws.amazon.com//AmazonS3/latest/userguide/MultiRegionAccessPoints.html)提供全域端點，可在其中路由 Amazon S3 請求流量 AWS 區域。

您可以使用[適用於 PHP 的 SDK](https://docs.aws.amazon.com//aws-sdk-php/v3/api/api-s3control-2018-08-20.html#createmultiregionaccesspoint)、另一個 AWS SDK、[S3 主控台或 AWS CLI ](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 Resource Name (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 和 第 3 適用於 PHP 的 AWS SDK 版管理秘密
<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) 將秘密標為刪除。

您可以在 GitHub 上 適用於 PHP 的 AWS SDK 取得 的所有範例程式碼。 [ GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code)

## 登入資料
<a name="examplecredentials"></a>

在執行範例程式碼之前，請先設定您的 AWS 登入資料，如中所述[AWS 使用第 3 適用於 PHP 的 AWS SDK 版向 驗證](credentials.md)。然後匯入 適用於 PHP 的 AWS SDK，如 中所述[安裝第 3 適用於 PHP 的 AWS SDK 版](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>

取得 Secrets Manager 使用 [ListSecrets](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-secretsmanager-2017-10-17.html#listsecrets) 操作存放的所有秘密清單。

 **匯入** 

```
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 Resource Name (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) 操作。

這會建立秘密的新版本。如果某個版本的秘密已存在，請在 `AWSCURRENT` 中新增含該值的 `VersionStages` 參數，以確保擷取該值時所用的是新的值。

 **匯入** 

```
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 函數來輪換秘密。Code [AWS Sample Catalog](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/)。

# 使用第 3 適用於 PHP 的 AWS SDK 版的 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)。雖然呼叫方法或結果的方式可能不同，但用戶端的功能在許多情況下會重疊。這兩個 APIs 也提供獨佔功能，因此您可以使用這兩個用戶端來存取所有功能。

本節中的範例都使用原始 `SesClient`。

第 3 適用於 PHP 的 AWS SDK 版的所有範例程式碼都可在 [ GitHub 上取得](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code)。

**Topics**
+ [驗證電子郵件地址](ses-verify.md)
+ [使用電子郵件範本](ses-template.md)
+ [管理電子郵件篩選條件](ses-filters.md)
+ [使用電子郵件規則](ses-rules.md)
+ [監控您的傳送活動](ses-send-email.md)
+ [授權寄件者](ses-sender-policy.md)

# 使用 Amazon SES API 和第 3 適用於 PHP 的 AWS SDK 版驗證電子郵件身分
<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) 移除電子郵件網域。

您可以在 GitHub 上 適用於 PHP 的 AWS SDK 取得 的所有範例程式碼。 [ GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code)

## 登入資料
<a name="examplecredentials"></a>

在執行範例程式碼之前，請先設定您的 AWS 登入資料，如中所述[AWS 使用第 3 適用於 PHP 的 AWS SDK 版向 驗證](credentials.md)。然後匯入 適用於 PHP 的 AWS SDK，如 中所述[安裝第 3 適用於 PHP 的 AWS SDK 版](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 和 第 3 適用於 PHP 的 AWS SDK 版建立自訂電子郵件範本
<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) 列出所有電子郵件範本。
+ 使用 [GetTemplate](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) 傳送範本電子郵件。

您可以在 GitHub 上 適用於 PHP 的 AWS SDK 取得 的所有範例程式碼。 [ GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code)

## 登入資料
<a name="examplecredentials"></a>

在執行範例程式碼之前，請先設定您的 AWS 登入資料，如中所述[AWS 使用第 3 適用於 PHP 的 AWS SDK 版向 驗證](credentials.md)。然後匯入 適用於 PHP 的 AWS SDK，如 中所述[安裝第 3 適用於 PHP 的 AWS SDK 版](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 和第 3 適用於 PHP 的 AWS SDK 版管理電子郵件篩選條件
<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) 刪除電子郵件篩選條件。

您可以在 GitHub 上 適用於 PHP 的 AWS SDK 取得 的所有範例程式碼。 [ GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code)

## 登入資料
<a name="examplecredentials"></a>

在執行範例程式碼之前，請先設定您的 AWS 登入資料，如中所述[AWS 使用第 3 適用於 PHP 的 AWS SDK 版向 驗證](credentials.md)。然後匯入 適用於 PHP 的 AWS SDK，如 中所述[安裝第 3 適用於 PHP 的 AWS SDK 版](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 區域中與 相關聯的 IP AWS 帳戶 地址篩選條件，請使用 [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 和第 3 適用於 PHP 的 AWS SDK 版建立和管理電子郵件規則
<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) 移除接收規則集。

您可以在 GitHub 上 適用於 PHP 的 AWS SDK 取得 的所有範例程式碼。 [ GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code)

## 登入資料
<a name="examplecredentials"></a>

在執行範例程式碼之前，請先設定您的 AWS 登入資料，如中所述[AWS 使用第 3 適用於 PHP 的 AWS SDK 版向 驗證](credentials.md)。然後匯入 適用於 PHP 的 AWS SDK，如 中所述[安裝第 3 適用於 PHP 的 AWS SDK 版](getting-started_installation.md)。

如需使用 Amazon SES 的詳細資訊，請參閱《[Amazon SES 開發人員指南](https://docs.aws.amazon.com/ses/latest/DeveloperGuide/)》。

## 建立接收規則集
<a name="create-a-receipt-rule-set"></a>

接收規則集包含一組接收規則。您的帳戶必須至少有一個關聯的接收規則集，您才能建立接收規則。若要建立接收規則集，請使用 [CreateReceiptRuleSet](https://docs.aws.amazon.com/ses/latest/APIReference/API_CreateReceiptRuleSet.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->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 和 第 3 適用於 PHP 的 AWS SDK 版監控您的傳送活動
<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) 監控您的傳送活動。

您可以在 GitHub 上 適用於 PHP 的 AWS SDK 取得 的所有範例程式碼。 [ GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code)

## 登入資料
<a name="examplecredentials"></a>

在執行範例程式碼之前，請先設定您的 AWS 登入資料，如中所述[AWS 使用第 3 適用於 PHP 的 AWS SDK 版向 驗證](credentials.md)。然後匯入 適用於 PHP 的 AWS SDK，如 中所述[安裝第 3 適用於 PHP 的 AWS SDK 版](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 和第 3 適用於 PHP 的 AWS SDK 版授權寄件者
<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) 對已獲授權的寄件者撤銷許可。

您可以在 GitHub 適用於 PHP 的 AWS SDK 上取得 的所有範例程式碼。 [ GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code)

## 登入資料
<a name="examplecredentials"></a>

在執行範例程式碼之前，請先設定您的 AWS 登入資料，如中所述[AWS 使用第 3 適用於 PHP 的 AWS SDK 版向 驗證](credentials.md)。然後匯入 適用於 PHP 的 AWS SDK，如 中所述[安裝第 3 適用於 PHP 的 AWS SDK 版](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 適用於 PHP 的 AWS SDK 版的 Amazon SNS 範例
<a name="sns-examples"></a>

Amazon Simple Notification Service (Amazon SNS) 是一種 Web 服務，可協調和管理訊息傳遞或傳送至訂閱端點或用戶端。

在 Amazon SNS 中，有兩種類型的用戶端：發佈者 （也稱為生產者） 和訂閱者 （也稱為消費者）。發佈者透過製作並傳送訊息到主題 (其為邏輯存取點和通訊管道) 與訂閱者進行非同步的通訊。訂閱者 （網路伺服器、電子郵件地址、Amazon SQS 佇列、 AWS Lambda 函數） 在訂閱主題時，會透過其中一個支援的通訊協定 (Amazon SQS、HTTP/HTTPS URLs、電子郵件 AWS SMS、Lambda) 取用或接收訊息或通知。

第 3 適用於 PHP 的 AWS SDK 版的所有範例程式碼都可在 [ 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)

# 使用第 3 適用於 PHP 的 AWS SDK 版管理 Amazon SNS 中的主題
<a name="sns-examples-managing-topics"></a>

若要傳送通知至 Amazon Simple Queue Service (Amazon SQS)、HTTP/HTTPS URLs AWS SMS、電子郵件或 AWS Lambda，您必須先建立主題來管理訊息交付給該主題的任何訂閱者。

就觀察者設計模式而言，主題即有如主旨。建立主題之後，您便要新增訂閱者，其將於訊息發佈至該主題時自動收到通知。

進一步了解如何使用第 [3 適用於 PHP 的 AWS SDK 版在 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)。

您可以在 GitHub 上 適用於 PHP 的 AWS SDK 取得 的所有範例程式碼。 [ GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code)

## 登入資料
<a name="examplecredentials"></a>

在執行範例程式碼之前，請先設定您的 AWS 登入資料，如中所述[AWS 使用第 3 適用於 PHP 的 AWS SDK 版向 驗證](credentials.md)。然後匯入 適用於 PHP 的 AWS SDK，如 中所述[安裝第 3 適用於 PHP 的 AWS SDK 版](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());
}
```

# 使用第 3 適用於 PHP 的 AWS SDK 版管理 Amazon SNS 中的訂閱
<a name="sns-examples-subscribing-unsubscribing-topics"></a>

使用 Amazon Simple Notification Service (Amazon SNS) 主題將通知傳送至 Amazon Simple Queue Service (Amazon SQS)、HTTP/HTTPS、電子郵件地址 AWS Server Migration Service (AWS SMS) 或 AWS Lambda。

訂閱會連接到主題，以管理對訂閱者的訊息傳送。進一步了解如何使用第 [3 適用於 PHP 的 AWS SDK 版在 Amazon SNS 中管理主題中](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) 傳送訊息給某主題的所有訂閱者。

如需使用 Amazon SNS 的詳細資訊，請參閱[使用 Amazon SNS 進行System-to-System傳訊](https://docs.aws.amazon.com/sns/latest/dg/sns-system-to-system-messaging.html)。

您可以在 GitHub 上 適用於 PHP 的 AWS SDK 取得 的所有範例程式碼。 [ GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code)

## 憑證
<a name="examplecredentials"></a>

在執行範例程式碼之前，請先設定您的 AWS 登入資料，如中所述[AWS 使用第 3 適用於 PHP 的 AWS SDK 版向 驗證](credentials.md)。然後匯入 適用於 PHP 的 AWS SDK，如 中所述[安裝第 3 適用於 PHP 的 AWS SDK 版](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 主題，取決於傳遞的參數所使用的值。本主題的其他範例將示範做法。

在此範例中，端點是電子郵件地址。確認字符會傳送至該電子郵件。收到確認符記後，可於三天內驗證訂閱。

 **匯入** 

```
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。確認字符會傳送至該網址。收到確認符記後，可於三天內驗證訂閱。

 **匯入** 

```
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 函數的訂閱，請使用[訂閱](https://docs.aws.amazon.com/sns/latest/api/API_Subscribe.html)操作。

您可以使用 訂閱方法將數個不同的端點訂閱至 Amazon SNS 主題，取決於傳遞的參數所使用的值。本主題的其他範例將示範做法。

在此範例中，端點是 Lambda 函數。確認字符會傳送至此 Lambda 函數。收到確認符記後，可於三天內驗證訂閱。

 **匯入** 

```
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());
}
```

## 訂閱文字簡訊至主題
<a name="subscribe-a-text-sms-to-a-topic"></a>

如需傳送簡訊至多個電話號碼，各號碼都要訂閱主題。

若要為電話號碼起始訂閱，請使用 [Subscribe](https://docs.aws.amazon.com/sns/latest/api/API_Subscribe.html) 操作。

您可以使用 訂閱方法將數個不同的端點訂閱至 Amazon SNS 主題，取決於傳遞的參數所使用的值。本主題的其他範例將示範做法。

在此範例中，端點是 E.164 格式的電話號碼，遵照國際電信通訊所採用的標準。

確認字符會傳送至該電話號碼。收到確認符記後，可於三天內驗證訂閱。

如需使用 Amazon SNS 傳送簡訊的替代方式，請參閱[使用第 3 版在 適用於 PHP 的 AWS SDK Amazon SNS 中傳送簡訊](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>

若要實際建立訂閱，端點擁有者必須使用最初建立訂閱時傳送的符記，確認其有意接收來自該主題的訊息，如前所述。確認符記的有效期為三天。三天之後，您可以透過建立新的訂閱重新傳送符記。

若要確認訂閱，請使用 [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>

若要列出指定區域中最多 100 個現有訂閱 AWS ，請使用 [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 主題的每個端點，請使用[發佈](https://docs.aws.amazon.com/sns/latest/api/API_Publish.html)操作。

建立包含發佈訊息參數的物件，包括訊息文字和 Amazon SNS 主題的 Amazon Resource Name (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());
}
```

# 使用第 3 適用於 PHP 的 AWS SDK 版在 Amazon SNS 中傳送簡訊
<a name="sns-examples-sending-sms"></a>

您可以使用 Amazon Simple Notification Service (Amazon SNS) 將文字訊息或簡訊傳送至啟用 SMS 的裝置。您可以直接傳送訊息至一組電話號碼，或一次傳送一則訊息至多組電話號碼，只要訂閱那些電話號碼到主題並且傳送您的訊息到該主題即可。

使用 Amazon SNS 指定簡訊的偏好設定，例如如何最佳化交付 （用於成本或可靠交付）、每月花費限制、如何記錄訊息交付，以及是否訂閱每日簡訊用量報告。系統會擷取這些偏好設定，並將其設定為 Amazon SNS 的 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) 擷取從您的帳戶傳送簡訊的預設設定。
+ 使用 [SetSMSAttributes](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-sns-2010-03-31.html#setsmsattributes) 更新從您的帳戶傳送簡訊的預設設定。
+ 使用 [CheckIfPhoneNumberISOptedOut](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-sns-2010-03-31.html#checkifphonenumberisoptedout) 檢查指定的電話號碼擁有者是否已選擇停止從您的帳戶接收簡訊。
+ 使用 [ListPhoneNumberOptedOut](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-sns-2010-03-31.html#listphonenumbersoptedout) 列出其擁有者已選擇停止從您的帳戶接收簡訊的電話號碼。
+ 使用 [Publish](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-sns-2010-03-31.html#publish) 直接傳送文字訊息 (簡訊) 至電話號碼。

如需使用 Amazon SNS 的詳細資訊，請參閱[將 Amazon SNS 用於使用者通知搭配行動電話號碼做為訂閱者 （傳送簡訊）](https://docs.aws.amazon.com/sns/latest/dg/sns-mobile-phone-number-as-subscriber.html)。

您可以在 GitHub 上 適用於 PHP 的 AWS SDK 取得 的所有範例程式碼。 [ GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code)

## 登入資料
<a name="examplecredentials"></a>

在執行範例程式碼之前，請先設定您的 AWS 登入資料，如中所述[AWS 使用第 3 適用於 PHP 的 AWS SDK 版向 驗證](credentials.md)。然後匯入 適用於 PHP 的 AWS SDK，如 中所述[安裝第 3 適用於 PHP 的 AWS SDK 版](getting-started_installation.md)。

## 取得 SMS 屬性
<a name="get-sms-attributes"></a>

若要擷取簡訊的預設設定，請使用 [GetSMSAttributes](https://docs.aws.amazon.com/sns/latest/api/API_GetSMSAttributes.html) 操作。

本範例將取得 `DefaultSMSType` 屬性。此屬性控制著簡訊的傳送方式，`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>

若要更新簡訊的預設設定，請使用 [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>

若要判斷指定的電話號碼擁有者是否已選擇停止從您的帳戶接收簡訊，請使用 [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>

若要擷取其擁有者已選擇停止從您的帳戶接收簡訊的電話號碼清單，請使用 [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>

若要直接交付文字訊息 (簡訊) 至電話號碼，請使用 [Publish](https://docs.aws.amazon.com/sns/latest/api/API_Publish.html) 操作。

本範例指定 E.164 格式的電話號碼，此為國際電信通訊所採用的標準。

每則簡訊最多可包含 140 個位元組。單次簡訊發佈動作的大小上限為 1,600 個位元組。

如需有關傳送簡訊的詳細資訊，請參閱[傳送簡訊](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());
}
```

# 使用第 3 適用於 PHP 的 AWS SDK 版的 Amazon SQS 範例
<a name="sqs-examples"></a>

Amazon Simple Queue Service (SQS) 是一種快速、可靠、可擴展、全受管的訊息佇列服務。Amazon SQS 可讓您解耦雲端應用程式的元件。Amazon SQS 包括具有高輸送量和at-least-once處理的標準佇列，以及提供 FIFO (first>-in、first>-out) 交付和恰好一次處理的 FIFO 佇列。

第 3 適用於 PHP 的 AWS SDK 版的所有範例程式碼都可在 [ GitHub 上取得](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code)。

**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)

# 使用第 3 適用於 PHP 的 AWS SDK 版在 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) 建立長輪詢佇列。

您可以在 GitHub 上 適用於 PHP 的 AWS SDK 取得 的所有範例程式碼。 [ GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code)

## 登入資料
<a name="examplecredentials"></a>

在執行範例程式碼之前，請先設定您的 AWS 登入資料，如中所述[AWS 使用第 3 適用於 PHP 的 AWS SDK 版向 驗證](credentials.md)。然後匯入 適用於 PHP 的 AWS SDK，如 中所述[安裝第 3 適用於 PHP 的 AWS SDK 版](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());
}
```

# 使用第 3 適用於 PHP 的 AWS SDK 版管理 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) 將佇列中的指定訊息可見性逾時變更為新值。

您可以在 GitHub 上 適用於 PHP 的 AWS SDK 取得 的所有範例程式碼。 [ GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code)

## 登入資料
<a name="examplecredentials"></a>

在執行範例程式碼之前，請先設定您的 AWS 登入資料，如中所述[AWS 使用第 3 適用於 PHP 的 AWS SDK 版向 驗證](credentials.md)。然後匯入 適用於 PHP 的 AWS SDK，如 中所述[安裝第 3 適用於 PHP 的 AWS SDK 版](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());
}
```

# 使用第 3 適用於 PHP 的 AWS SDK 版在 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) 從佇列刪除訊息。

您可以在 GitHub 上 適用於 PHP 的 AWS SDK 取得 的所有範例程式碼。 [ GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code)

## 登入資料
<a name="examplecredentials"></a>

在執行範例程式碼之前，請先設定您的 AWS 登入資料，如中所述[AWS 使用第 3 適用於 PHP 的 AWS SDK 版向 驗證](credentials.md)。然後匯入 適用於 PHP 的 AWS SDK，如 中所述[安裝第 3 適用於 PHP 的 AWS SDK 版](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());
}
```

# 在 Amazon SQS 中使用無效字母佇列搭配第 3 適用於 PHP 的 AWS SDK 版
<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) 啟用無效字母佇列。

您可以在 GitHub 上 適用於 PHP 的 AWS SDK 取得 的所有範例程式碼。 [ GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code)

## 登入資料
<a name="examplecredentials"></a>

在執行範例程式碼之前，請先設定您的 AWS 登入資料，如中所述[AWS 使用第 3 適用於 PHP 的 AWS SDK 版向 驗證](credentials.md)。然後匯入 適用於 PHP 的 AWS SDK，如 中所述[安裝第 3 適用於 PHP 的 AWS SDK 版](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());
}
```

# 將 Amazon SQS 中的佇列與第 3 適用於 PHP 的 AWS SDK 版搭配使用
<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) 刪除指定的佇列。

您可以在 GitHub 上 適用於 PHP 的 AWS SDK 取得 的所有範例程式碼。 [ GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code)

## 登入資料
<a name="examplecredentials"></a>

在執行範例程式碼之前，請先設定您的 AWS 登入資料，如中所述[AWS 使用第 3 適用於 PHP 的 AWS SDK 版向 驗證](credentials.md)。然後匯入 適用於 PHP 的 AWS SDK，如 中所述[安裝第 3 適用於 PHP 的 AWS SDK 版](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());
}
```

# 使用第 3 適用於 PHP 的 AWS SDK 版將事件傳送至 Amazon EventBridge 全域端點
<a name="eventbridge-examples"></a>

您可以使用 [Amazon EventBridge 全域端點](https://docs.aws.amazon.com//eventbridge/latest/userguide/eb-global-endpoints.html)來改善事件驅動應用程式的可用性和可靠性。

[設定](https://docs.aws.amazon.com//eventbridge/latest/userguide/eb-global-endpoints.html#eb-ge-create-endpoint) EventBridge 全域端點之後，您可以使用適用於 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 全域端點的詳細資訊。