Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
awsdocs
GitHub Repository: awsdocs/amazon-s3-developer-guide
Path: blob/master/code_examples/php_examples/S3examples/s3-deleting-multi-objects-versioned.php
4084 views
1
<?php
2
// Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
3
// SPDX-License-Identifier: MIT-0 (For details, see https://github.com/awsdocs/amazon-s3-developer-guide/blob/master/LICENSE-SAMPLECODE )
4
5
require 'vendor/autoload.php';
6
7
use Aws\S3\S3Client;
8
9
$bucket = '*** Your Bucket Name ***';
10
$keyname = '*** Your Object Key ***';
11
12
$s3 = new S3Client([
13
'version' => 'latest',
14
'region' => 'us-east-1'
15
]);
16
17
// 1. Enable object versioning for the bucket.
18
$s3->putBucketVersioning([
19
'Bucket' => $bucket,
20
'Status' => 'Enabled',
21
]);
22
23
// 2. Create a few versions of an object.
24
for ($i = 1; $i <= 3; $i++) {
25
$s3->putObject([
26
'Bucket' => $bucket,
27
'Key' => $keyname,
28
'Body' => "content {$i}",
29
]);
30
}
31
32
// 3. List the objects versions and get the keys and version IDs.
33
$versions = $s3->listObjectVersions(['Bucket' => $bucket])
34
->getPath('Versions');
35
36
// 4. Delete the object versions.
37
$s3->deleteObjects([
38
'Bucket' => $bucket,
39
'Delete' => [
40
'Objects' => array_map(function ($version) {
41
return [
42
'Key' => $version['Key'],
43
'VersionId' => $version['VersionId']
44
}, $versions),
45
],
46
]);
47
48
echo "The following objects were deleted successfully:". PHP_EOL;
49
foreach ($result['Deleted'] as $object) {
50
echo "Key: {$object['Key']}, VersionId: {$object['VersionId']}" . PHP_EOL;
51
}
52
53
echo PHP_EOL . "The following objects could not be deleted:" . PHP_EOL;
54
foreach ($result['Errors'] as $object) {
55
echo "Key: {$object['Key']}, VersionId: {$object['VersionId']}" . PHP_EOL;
56
}
57
58
// 5. Suspend object versioning for the bucket.
59
$s3->putBucketVersioning([
60
'Bucket' => $bucket,
61
'Status' => 'Suspended',
62
]);
63
64