

Die vorliegende Übersetzung wurde maschinell erstellt. Im Falle eines Konflikts oder eines Widerspruchs zwischen dieser übersetzten Fassung und der englischen Fassung (einschließlich infolge von Verzögerungen bei der Übersetzung) ist die englische Fassung maßgeblich.

# CloudFront Amazon-Beispiele mit der AWS SDK für PHP Version 3
<a name="cf-examples"></a>

Amazon CloudFront ist ein AWS Webservice, der die Bereitstellung statischer und dynamischer Webinhalte von Ihrem eigenen Webserver oder einem AWS Server wie Amazon S3 beschleunigt. CloudFront stellt Inhalte über ein weltweites Netzwerk von Rechenzentren bereit, die als Edge-Standorte bezeichnet werden. Wenn ein Benutzer Inhalte anfordert, mit denen Sie sie verteilen CloudFront, wird er an den Edge-Standort weitergeleitet, der die niedrigste Latenz bietet. Falls sich der Inhalt dort noch nicht im Cache befindet, ruft CloudFront eine Kopie vom Ursprungs-Server ab, stellt sie bereit, und speichert sie dann für zukünftige Anfragen im Cache.

Weitere Informationen CloudFront dazu finden Sie im [Amazon CloudFront Developer Guide](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/).

Der gesamte Beispielcode für die AWS SDK für PHP Version 3 ist [hier verfügbar GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code).

# Verwaltung von CloudFront Amazon-Distributionen mithilfe der CloudFront API und der AWS SDK für PHP Version 3
<a name="cloudfront-example-distribution"></a>

Amazon CloudFront speichert Inhalte an weltweiten Edge-Standorten im Cache, um die Verteilung statischer und dynamischer Dateien zu beschleunigen, die Sie auf Ihrem eigenen Server oder auf einem Amazon-Dienst wie Amazon S3 und Amazon EC2 speichern. Wenn Benutzer Inhalte von Ihrer Website anfordern, werden sie CloudFront vom nächstgelegenen Edge-Standort aus bereitgestellt, sofern die Datei dort zwischengespeichert ist. Andernfalls wird eine Kopie der Datei CloudFront abgerufen, bereitgestellt und dann für die nächste Anfrage zwischengespeichert. Das Speichern von Inhalten im Cache eines Edge-Standorts reduziert die Latenz von ähnlichen Benutzeranfragen in dieser Region.

Für jede CloudFront Verteilung, die Sie erstellen, geben Sie an, wo sich der Inhalt befindet und wie er verteilt werden soll, wenn Benutzer Anfragen stellen. Dieses Thema konzentriert sich auf Verteilungen von statischen und dynamischen Dateien wie HTML-, CSS-, JSON- und Bilddateien. Informationen zur Verwendung CloudFront mit Video-on-Demand finden Sie unter [On-Demand-Video und Live-Streaming mit CloudFront](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/on-demand-streaming-video.html).

In den nachstehenden Beispielen wird Folgendes veranschaulicht:
+ Erstellen Sie eine Distribution mit [CreateDistribution](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-cloudfront-2018-11-05.html#createdistribution).
+ Holen Sie sich eine Distribution mit [GetDistribution](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-cloudfront-2018-11-05.html#getdistribution).
+ Listet Distributionen auf mit [ListDistributions](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-cloudfront-2018-11-05.html#listdistributions).
+ Aktualisieren Sie Distributionen mit. [UpdateDistributions](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-cloudfront-2018-11-05.html#updatedistribution)
+ Deaktivieren Sie Distributionen mit. [DisableDistribution](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-cloudfront-2018-11-05.html#disabledistribution)
+ Löschen Sie Distributionen mit. [DeleteDistributions](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-cloudfront-2018-11-05.html#deletedistribution)

Der gesamte Beispielcode für AWS SDK für PHP ist [hier verfügbar GitHub.](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code)

## Anmeldeinformationen
<a name="examplecredentials"></a>

Bevor Sie den Beispielcode ausführen, konfigurieren Sie Ihre AWS Anmeldeinformationen wie unter beschrieben[Authentifizierung AWS mit AWS SDK für PHP Version 3](credentials.md). Importieren Sie dann die AWS SDK für PHP, wie unter beschrieben[Installation der AWS SDK für PHP Version 3](getting-started_installation.md).

Weitere Informationen zur Verwendung von Amazon CloudFront finden Sie im [Amazon CloudFront Developer Guide](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/).

## Erstellen Sie eine CloudFront Distribution
<a name="create-a-cf-distribution"></a>

Erstellen Sie eine Distribution aus einem Amazon S3 S3-Bucket. Im folgenden Beispiel werden optionale Parameter auskommentiert, aber Standardwerte werden angezeigt. Zum Hinzufügen von Anpassungen zu Ihrer Verteilung kommentieren Sie sowohl den Wert als auch den Parameter in `$distribution` aus.

Verwenden Sie den [CreateDistribution](https://docs.aws.amazon.com/cloudfront/latest/APIReference/API_CreateDistribution.html)Vorgang, um eine CloudFront Verteilung zu erstellen.

 **Importe** 

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

use Aws\Exception\AwsException;
```

 **Beispiel-Code** 

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

## Rufen Sie eine CloudFront Verteilung ab
<a name="retrieve-a-cf-distribution"></a>

Verwenden Sie den [GetDistribution](https://docs.aws.amazon.com/cloudfront/latest/APIReference/API_GetDistribution.html)Vorgang, um den Status und die Details einer bestimmten CloudFront Verteilung abzurufen.

 **Importe** 

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

use Aws\Exception\AwsException;
```

 **Beispiel-Code** 

```
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 Verteilungen auflisten
<a name="list-cf-distributions"></a>

Rufen Sie mithilfe dieses Vorgangs eine Liste der vorhandenen CloudFront Distributionen in der angegebenen AWS Region von Ihrem Girokonto ab. [ListDistributions](https://docs.aws.amazon.com/cloudfront/latest/APIReference/API_ListDistributions.html)

 **Importe** 

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

use Aws\Exception\AwsException;
```

 **Beispiel-Code** 

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

## Aktualisieren Sie eine Distribution CloudFront
<a name="update-a-cf-distribution"></a>

Das Aktualisieren einer CloudFront Distribution ähnelt dem Erstellen einer Distribution. Bei der Aktualisierung einer Verteilung sind jedoch mehr Felder erforderlich und alle Werte müssen berücksichtigt werden. Zur Vornahme von Änderungen an einer vorhandenen Verteilung empfehlen wir, zuerst die vorhandene Verteilung abzurufen und die zu aktualisierenden Werte im `$distribution`-Array zu ändern.

Verwenden Sie den [UpdateDistribution](https://docs.aws.amazon.com/cloudfront/latest/APIReference/API_UpdateDistribution.html)Vorgang, um eine angegebene CloudFront Distribution zu aktualisieren.

 **Importe** 

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

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

 **Beispiel-Code** 

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

## Deaktiviert eine CloudFront Distribution
<a name="disable-a-cf-distribution"></a>

Zum Deaktivieren oder Entfernen einer Verteilung ändern Sie ihren Status von „Bereitgestellt“ in „Deaktiviert“.

Verwenden Sie den [DisableDistribution](https://docs.aws.amazon.com/cloudfront/latest/APIReference/API_DisableDistribution.html)Vorgang, um die angegebene CloudFront Distribution zu deaktivieren.

 **Importe** 

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

use Aws\Exception\AwsException;
```

 **Beispiel-Code** 

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

## Löscht eine CloudFront Distribution
<a name="delete-a-cf-distribution"></a>

Sobald eine Verteilung den Status „Deaktiviert“ aufweist, können Sie sie löschen.

Verwenden Sie den [DeleteDistribution](https://docs.aws.amazon.com/cloudfront/latest/APIReference/API_DeleteDistribution.html)Vorgang, um eine angegebene CloudFront Distribution zu entfernen.

 **Importe** 

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

use Aws\Exception\AwsException;
```

 **Beispiel-Code** 

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

# Verwaltung von CloudFront Amazon-Invalidierungen mithilfe der CloudFront API und der Version 3 AWS SDK für PHP
<a name="cloudfront-example-invalidation"></a>

Amazon CloudFront speichert Kopien statischer und dynamischer Dateien an weltweiten Edge-Standorten im Cache. Erstellen Sie zum Entfernen oder Aktualisieren einer Datei auf allen Edge-Standorten eine Aufhebung für alle Dateien bzw. für eine Gruppe von Dateien.

Die ersten 1.000 Aufhebungen jedes Kalendermonats sind kostenlos. Weitere Informationen zum Entfernen von Inhalten von einem CloudFront Edge-Standort finden Sie unter Dateien für [ungültig erklären](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/Invalidation.html).

In den nachstehenden Beispielen wird Folgendes veranschaulicht:
+ Erstellen Sie eine Invalidierung der Verteilung mit. [CreateInvalidation](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-cloudfront-2018-11-05.html#createinvalidation)
+ Rufen Sie eine Distributions-Invalidierung ab mit. [GetInvalidation](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-cloudfront-2018-11-05.html#getinvalidation)
+ Listet Distributionen auf mit. [ListInvalidations](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-cloudfront-2018-11-05.html#listinvalidations)

Der gesamte Beispielcode für AWS SDK für PHP ist [hier verfügbar GitHub.](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code)

## Anmeldeinformationen
<a name="examplecredentials"></a>

Bevor Sie den Beispielcode ausführen, konfigurieren Sie Ihre AWS Anmeldeinformationen wie unter beschrieben[Authentifizierung AWS mit AWS SDK für PHP Version 3](credentials.md). Importieren Sie dann die AWS SDK für PHP, wie unter beschrieben[Installation der AWS SDK für PHP Version 3](getting-started_installation.md).

Weitere Informationen zur Verwendung von Amazon CloudFront finden Sie im [Amazon CloudFront Developer Guide](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/).

## Erstellen Sie eine Invalidierung der Distribution
<a name="create-a-distribution-invalidation"></a>

Erstellen Sie eine Invalidierung der CloudFront Distribution, indem Sie den Pfad für die Dateien angeben, die Sie entfernen müssen. Dieses Beispiel hebt die Gültigkeit aller Dateien in der Verteilung auf, aber Sie können bestimmte Dateien unter `Items` identifizieren.

Verwenden Sie den Vorgang, um eine Invalidierung der CloudFront [CreateInvalidation](https://docs.aws.amazon.com/cloudfront/latest/APIReference/API_CreateInvalidation.html)Verteilung zu erstellen.

 **Importe** 

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

use Aws\Exception\AwsException;
```

 **Beispiel-Code** 

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

## Holen Sie sich eine Distributions-Invalidierung
<a name="get-a-distribution-invalidation"></a>

Verwenden Sie den Vorgang, um den Status und die Details einer CloudFront Verteilung für ungültig zu erklären. [GetInvalidation](https://docs.aws.amazon.com/cloudfront/latest/APIReference/API_GetInvalidation.html)

 **Importe** 

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

use Aws\Exception\AwsException;
```

 **Beispiel-Code** 

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

## Ungültigerklärungen von Verteilungen auflisten
<a name="list-distribution-invalidations"></a>

Verwenden Sie den Vorgang, um alle aktuellen CloudFront Verteilungsungültigkeiten aufzulisten. [ListInvalidations](https://docs.aws.amazon.com/cloudfront/latest/APIReference/API_ListInvalidations.html)

 **Importe** 

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

use Aws\Exception\AwsException;
```

 **Beispiel-Code** 

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

# Amazon CloudFront URLs mit AWS SDK für PHP Version 3 signieren
<a name="cloudfront-example-signed-url"></a>

Signiert URLs ermöglichen es Ihnen, Benutzern Zugriff auf Ihre privaten Inhalte zu gewähren. Eine signierte URL enthält zusätzliche Informationen (z. B. Ablaufzeit), mit denen Sie den Zugriff auf Ihre Inhalte besser kontrollieren können. Diese zusätzlichen Informationen sind in einer Richtlinienanweisung enthalten, die entweder auf einer vordefinierten oder einer benutzerdefinierten Richtlinie basieren. Informationen darüber, wie Sie private Distributionen einrichten und warum Sie unterschreiben müssen URLs, finden Sie unter [Serving Private Content through Amazon CloudFront im Amazon](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/PrivateContent.html) CloudFront Developer Guide.
+ Erstellen Sie mit [getSignedUrl](https://docs.aws.amazon.com/aws-sdk-php/v3/api/class-Aws.CloudFront.CloudFrontClient.html#_getSignedUrl) eine signierte CloudFront Amazon-URL.
+ Erstellen Sie ein signiertes CloudFront Amazon-Cookie mit [getSignedCookie](https://docs.aws.amazon.com/aws-sdk-php/v3/api/class-Aws.CloudFront.CloudFrontClient.html#_getSignedCookie).

Der gesamte Beispielcode für die AWS SDK für PHP ist [hier verfügbar GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code).

## Anmeldeinformationen
<a name="examplecredentials"></a>

Bevor Sie den Beispielcode ausführen, konfigurieren Sie Ihre AWS Anmeldeinformationen wie unter beschrieben[Authentifizierung AWS mit AWS SDK für PHP Version 3](credentials.md). Importieren Sie dann die AWS SDK für PHP, wie unter beschrieben[Installation der AWS SDK für PHP Version 3](getting-started_installation.md).

Weitere Informationen zur Verwendung von Amazon CloudFront finden Sie im [Amazon CloudFront Developer Guide](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/).

## Signieren CloudFront URLs für private Distributionen
<a name="signing-cf-urls-for-private-distributions"></a>

Sie können eine URL mit dem CloudFront Client im SDK signieren. Zuerst müssen Sie ein Objekt `CloudFrontClient` erstellen. Sie können eine CloudFront URL für eine Videoressource entweder mithilfe einer vorgefertigten oder einer benutzerdefinierten Richtlinie signieren.

 **Importe** 

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

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

 **Beispiel-Code** 

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

## Verwenden Sie beim Erstellen eine benutzerdefinierte Richtlinie CloudFront URLs
<a name="use-a-custom-policy-when-creating-cf-urls"></a>

Um eine benutzerdefinierte Richtlinie zu verwenden, geben Sie den Schlüssel `policy` anstelle von `expires` an.

 **Importe** 

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

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

 **Beispiel-Code** 

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

## Verwenden Sie eine CloudFront signierte URL
<a name="use-a-cf-signed-url"></a>

Die Form der signierten URL unterscheidet sich in Abhängigkeit davon, ob die URL, die Sie signieren, das Schema „HTTP“ oder „RTMP“ verwendet. Im Fall von „HTTP“ wird die vollständige, absolute URL zurückgegeben. Für „RTMP“ wird nur die relative URL zurückgegeben. Dies liegt daran, dass einige Player den Host und den Pfad als separate Parameter benötigen.

Das folgende Beispiel zeigt, wie Sie die signierte URL verwenden können, um eine Webseite zu erstellen, auf der ein Video mit angezeigt wird [JWPlayer](http://www.longtailvideo.com/jw-player/). Dieselbe Technik würde auch für andere Player gelten [FlowPlayer](http://flowplayer.org/), erfordert aber einen anderen clientseitigen Code.

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

## Signieren von CloudFront Cookies für private Distributionen
<a name="signing-cf-cookies-for-private-distributions"></a>

Als Alternative zu signierten URLs Cookies können Sie Kunden auch über signierte Cookies Zugriff auf eine private Distribution gewähren. Signierte Cookies ermöglichen Ihnen den Zugriff auf mehrere Dateien mit beschränkten Rechten, z. B. alle Dateien für ein Video im HLS-Format oder alle Dateien im Bereich der Abonnenten einer Website. Weitere Informationen darüber, warum Sie signierte Cookies anstelle von signierten Cookies verwenden möchten URLs (oder umgekehrt), finden Sie unter [Wählen zwischen signierten URLs und signierten Cookies](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/private-content-choosing-signed-urls-cookies.html) im Amazon CloudFront Developer Guide.

Das Erstellen eines signierten Cookies ähnelt dem Erstellen einer signierten URL. Der einzige Unterschied ist die aufgerufene Methode (`getSignedCookie`statt `getSignedUrl`).

 **Importe** 

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

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

 **Beispiel-Code** 

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

## Verwenden Sie beim Erstellen von CloudFront Cookies eine benutzerdefinierte Richtlinie
<a name="use-a-custom-policy-when-creating-cf-cookies"></a>

Wie bei `getSignedUrl` können Sie anstelle eines Parameters `'policy'` einen Parameter `expires` und einen Parameter `url` verwenden, um einen Cookie mit einer benutzerdefinierten Richtlinie zu unterschreiben. Eine benutzerdefinierte Richtlinie kann Platzhalter im Ressourcenschlüssel enthalten. Dadurch können Sie ein einzelnes signiertes Cookie für mehrere Dateien erstellen.

 `getSignedCookie` gibt ein Array von Schlüssel-Wert-Paaren zurück, die alle als Cookies festgelegt werden müssen, um den Zugriff auf eine private Distribution zu ermöglichen.

 **Importe** 

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

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

 **Beispiel-Code** 

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

## Sende CloudFront Cookies an den Guzzle-Client
<a name="send-cf-cookies-to-guzzle-client"></a>

Sie können diese Cookies auch an eine `GuzzleHttp\Cookie\CookieJar` zur Verwendung mit einem Guzzle-Client übergeben.

```
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');
```

Weitere Informationen finden Sie unter [Verwenden signierter Cookies](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/private-content-signed-cookies.html) im Amazon CloudFront Developer Guide.