DeleteDistribution.php - AWS Code Sample

DeleteDistribution.php

DeleteDistribution.php demonstrates how to delete an Amazon CloudFront distribution that has been disabled.

<?php /* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. SPDX-License-Identifier: Apache-2.0 */ require 'vendor/autoload.php'; use Aws\CloudFront\CloudFrontClient; use Aws\Exception\AwsException; /* //////////////////////////////////////////////////////////////////////////// * Purpose: Deletes an Amazon CloudFront distribution. * * Prerequisites: An existing Amazon CloudFront distribution. The * distribution must be disabled first. * * Inputs: * - $cloudFrontClient: An initialized AWS SDK for PHP SDK client * for CloudFront. * - $distributionId: The distribution's ID. * - $eTag: The ETag header value for the distribution. This value comes from * the companion getDistributionETag function. * * Returns: Information about the deletion request; otherwise, * the error message. * ///////////////////////////////////////////////////////////////////////// */ 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();

Sample Details

Service: cloudfront

Last tested: 2020-04-21

Author: pccornel (AWS)

Type: full-example