S3: Delete Multiple Objects and Check Per-Object Errors
See more S3 - HTTP Examples
Uses Chilkat.Http with Amazon S3 general purpose buckets and Signature Version 4. These examples do not cover directory buckets/S3 Express, access-point ARNs, Outposts, or other specialized endpoints. They target the commercial AWS partition; other partitions need their documented endpoint suffix.
Load private qa_data/aws/s3.json containing nonempty string fields access_key and secret_key, plus session_token for temporary credentials. Prefer short-lived role credentials. These samples do not discover AWS profiles or refresh credentials. Set the bucket's actual region and replace sample bucket names and object keys. TLS certificate verification is explicitly enabled. Keep detailed HTTP diagnostics private because they can contain credentials or presigned URLs.
Sends an explicit DeleteObjects request with Http.HttpStr and receives the original HttpResponse. XML APIs safely serialize up to 1,000 object identifiers. The request uses quiet mode; successful entries may be absent. HTTP 200 can still contain per-object errors, so every Error element is inspected before reporting success.
The sample uses Crypt2 to sign this fixed POST /?delete= request with SigV4, including Content-MD5, the SHA-256 payload hash, date, and optional session token. Keep the system clock accurate. Do not alter signed components after signing. This signing block is specific to this operation, not a general URL canonicalizer. See AWS header-signing rules.
Requires s3:DeleteObject, and s3:DeleteObjectVersion for explicit versions. Version-specific deletion is permanent. Without a version ID, a versioning-enabled bucket normally gains delete markers instead. Missing keys count as successful deletes. MFA Delete, retention, and legal holds may affect results. Retry only failed identifiers when appropriate, rather than repeating successful versioned deletes.
Chilkat PHP ActiveX Downloads
<?php
$success = 0;
$stringCompare = new COM("Chilkat.StringBuilder");
// This example requires the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.
// Load private credentials; never put access keys or session tokens in source.
$credentials = new COM("Chilkat.JsonObject");
$credentials->Strict = 1;
$success = $credentials->LoadFile('qa_data/aws/s3.json');
if ($success != 1) {
print 'Could not load private S3 credentials.' . "\n";
exit;
}
$stringCompare->SetString($credentials->stringOf('access_key'));
$stringMatch1 = $stringCompare->ContentsEqual('',1);
if (($credentials->JsonTypeOf('access_key') != 1) or ($stringMatch1 == 1)) {
print 'Missing or invalid access_key.' . "\n";
exit;
}
$stringCompare->SetString($credentials->stringOf('secret_key'));
$stringMatch2 = $stringCompare->ContentsEqual('',1);
if (($credentials->JsonTypeOf('secret_key') != 1) or ($stringMatch2 == 1)) {
print 'Missing or invalid secret_key.' . "\n";
exit;
}
$http = new COM("Chilkat.Http");
$http->AwsAccessKey = $credentials->stringOf('access_key');
$http->AwsSecretKey = $credentials->stringOf('secret_key');
if ($credentials->HasMember('session_token') == 1) {
$stringCompare->SetString($credentials->stringOf('session_token'));
$stringMatch3 = $stringCompare->ContentsEqual('',1);
if (($credentials->JsonTypeOf('session_token') != 1) or ($stringMatch3 == 1)) {
print 'session_token must be a nonempty string when supplied.' . "\n";
exit;
}
$http->AwsSessionToken = $credentials->stringOf('session_token');
}
// Current Chilkat uses SigV4 by default. Do not select deprecated SigV2.
// Set the actual bucket region, not the caller's location.
$region = 'us-west-2';
$http->AwsRegion = $region;
$endpoint = new COM("Chilkat.StringBuilder");
$endpoint->Append('s3.');
$endpoint->Append($region);
$endpoint->Append('.amazonaws.com');
$http->AwsEndpoint = $endpoint->getAsString();
$http->RequireSslCertVerify = 1;
$http->FollowRedirects = 0;
// A region redirect is not success. Correct the endpoint and signing region.
$bucketName = 'your-bucket-name';
$deleteRequest = new COM("Chilkat.Xml");
$deleteRequest->Tag = 'Delete';
$deleteRequest->AddAttribute('xmlns','http://s3.amazonaws.com/doc/2006-03-01/');
$deleteRequest->UpdateChildContent('Quiet','true');
// XML APIs escape key text. Do NOT URL-encode keys in this XML body.
$deleteRequest->UpdateChildContent('Object[0]|Key','images/seahorse.jpg');
$deleteRequest->UpdateChildContent('Object[1]|Key','images/starfish.jpg');
// For permanent deletion of a specific version, add Object[i]|VersionId
// deliberately. Use separate XML elements, not an embedded string convention.
if (($deleteRequest->NumChildrenHavingTag('Object') < 1) or ($deleteRequest->NumChildrenHavingTag('Object') > 1000)) {
print 'Use a batch of 1 to 1,000 object identifiers.' . "\n";
exit;
}
$requestBody = $deleteRequest->getXml();
// Sign this exact POST /?delete= request, including its UTF-8 body and MD5.
// Do not change signed headers, body, endpoint, or query after signing.
$host = new COM("Chilkat.StringBuilder");
$host->Append($bucketName);
$host->Append('.');
$host->Append($endpoint->getAsString());
$now = new COM("Chilkat.CkDateTime");
$success = $now->SetFromCurrentSystemTime();
if ($success != 1) {
print 'Could not read system time.' . "\n";
exit;
}
$timestamp = new COM("Chilkat.StringBuilder");
$timestamp->Append($now->getAsTimestamp(0));
$removedDashes = $timestamp->Replace('-','');
$removedColons = $timestamp->Replace(':','');
$amzDate = $timestamp->getAsString();
$dateStamp = $timestamp->getRange(0,8,0);
$crypt = new COM("Chilkat.Crypt2");
$crypt->Charset = 'utf-8';
$crypt->HashAlgorithm = 'md5';
$crypt->EncodingMode = 'base64';
$contentMd5 = $crypt->hashStringENC($requestBody);
if ($crypt->LastMethodSuccess != 1) {
print 'Could not hash delete body.' . "\n";
exit;
}
$crypt->HashAlgorithm = 'sha256';
$crypt->EncodingMode = 'hexlower';
$payloadHash = $crypt->hashStringENC($requestBody);
if ($crypt->LastMethodSuccess != 1) {
print 'Could not hash delete body.' . "\n";
exit;
}
$signedHeaders = new COM("Chilkat.StringBuilder");
$signedHeaders->Append('content-md5;host;x-amz-content-sha256;x-amz-date');
$canonical = new COM("Chilkat.StringBuilder");
$canonical->Append('POST\n/\ndelete=\ncontent-md5:');
$canonical->Append($contentMd5);
$canonical->Append('\nhost:');
$canonical->Append($host->getAsString());
$canonical->Append('\nx-amz-content-sha256:');
$canonical->Append($payloadHash);
$canonical->Append('\nx-amz-date:');
$canonical->Append($amzDate);
$canonical->Append('\n');
if ($credentials->HasMember('session_token') == 1) {
$signedHeaders->Append(';x-amz-security-token');
$canonical->Append('x-amz-security-token:');
$canonical->Append($credentials->stringOf('session_token'));
$canonical->Append('\n');
$http->SetRequestHeader('x-amz-security-token',$credentials->stringOf('session_token'));
}
$canonical->Append('\n');
$canonical->Append($signedHeaders->getAsString());
$canonical->Append('\n');
$canonical->Append($payloadHash);
$canonicalHash = $crypt->hashStringENC($canonical->getAsString());
if ($crypt->LastMethodSuccess != 1) {
print 'Could not hash canonical request.' . "\n";
exit;
}
$scope = new COM("Chilkat.StringBuilder");
$scope->Append($dateStamp);
$scope->Append('/');
$scope->Append($region);
$scope->Append('/s3/aws4_request');
$stringToSign = new COM("Chilkat.StringBuilder");
$stringToSign->Append('AWS4-HMAC-SHA256\n');
$stringToSign->Append($amzDate);
$stringToSign->Append('\n');
$stringToSign->Append($scope->getAsString());
$stringToSign->Append('\n');
$stringToSign->Append($canonicalHash);
$initialKey = new COM("Chilkat.StringBuilder");
$initialKey->Append('AWS4');
$initialKey->Append($credentials->stringOf('secret_key'));
$crypt->MacAlgorithm = 'hmac';
$success = $crypt->SetMacKeyString($initialKey->getAsString());
if ($success != 1) {
print 'Could not set signing key.' . "\n";
exit;
}
$derivedKey = $crypt->macStringENC($dateStamp);
if ($crypt->LastMethodSuccess != 1) {
print 'Could not derive date signing key.' . "\n";
exit;
}
$success = $crypt->SetMacKeyEncoded($derivedKey,'hex');
if ($success != 1) {
print 'Could not set derived signing key.' . "\n";
exit;
}
$derivedKey = $crypt->macStringENC($region);
if ($crypt->LastMethodSuccess != 1) {
print 'Could not derive signing key.' . "\n";
exit;
}
$success = $crypt->SetMacKeyEncoded($derivedKey,'hex');
if ($success != 1) {
print 'Could not set derived signing key.' . "\n";
exit;
}
$derivedKey = $crypt->macStringENC('s3');
if ($crypt->LastMethodSuccess != 1) {
print 'Could not derive signing key.' . "\n";
exit;
}
$success = $crypt->SetMacKeyEncoded($derivedKey,'hex');
if ($success != 1) {
print 'Could not set derived signing key.' . "\n";
exit;
}
$derivedKey = $crypt->macStringENC('aws4_request');
if ($crypt->LastMethodSuccess != 1) {
print 'Could not derive signing key.' . "\n";
exit;
}
$success = $crypt->SetMacKeyEncoded($derivedKey,'hex');
if ($success != 1) {
print 'Could not set final signing key.' . "\n";
exit;
}
$signature = $crypt->macStringENC($stringToSign->getAsString());
if ($crypt->LastMethodSuccess != 1) {
print 'Could not sign delete request.' . "\n";
exit;
}
$authorization = new COM("Chilkat.StringBuilder");
$authorization->Append('AWS4-HMAC-SHA256 Credential=');
$authorization->Append($credentials->stringOf('access_key'));
$authorization->Append('/');
$authorization->Append($scope->getAsString());
$authorization->Append(', SignedHeaders=');
$authorization->Append($signedHeaders->getAsString());
$authorization->Append(', Signature=');
$authorization->Append($signature);
$http->SetRequestHeader('Authorization',$authorization->getAsString());
$http->SetRequestHeader('Content-MD5',$contentMd5);
$http->SetRequestHeader('x-amz-content-sha256',$payloadHash);
$http->SetRequestHeader('x-amz-date',$amzDate);
$requestUrl = new COM("Chilkat.StringBuilder");
$requestUrl->Append('https://');
$requestUrl->Append($host->getAsString());
$requestUrl->Append('/?delete=');
$response = new COM("Chilkat.HttpResponse");
$success = $http->HttpStr('POST',$requestUrl->getAsString(),$requestBody,'utf-8','application/xml',$response);
if ($success != 1) {
print 'Request failed (transport or S3 error). HTTP status: ' . $http->LastStatus . "\n";
// Inspect LastErrorText privately. Do not log credentials or signed URLs.
exit;
}
if ($response->StatusCode != 200) {
print 'Unexpected HTTP status: ' . $response->StatusCode . "\n";
exit;
}
// HTTP 200 can contain per-object errors. Inspect the actual XML body.
$xml = new COM("Chilkat.Xml");
$success = $xml->LoadXml($response->BodyStr);
if ($success != 1) {
print 'Invalid XML response.' . "\n";
exit;
}
$stringCompare->SetString($xml->Tag);
$stringMatch4 = $stringCompare->ContentsEqual('DeleteResult',1);
if ($stringMatch4 != 1) {
print 'Unexpected XML response root.' . "\n";
exit;
}
$failures = $xml->NumChildrenHavingTag('Error');
$i = 0;
while (($i < $failures)) {
$xml->I = $i;
print 'Failed key: ' . $xml->getChildContent('Error[i]|Key') . "\n";
print 'Error code: ' . $xml->getChildContent('Error[i]|Code') . "\n";
$i = $i + 1;
}
if ($failures != 0) {
print 'One or more objects were not deleted. Retry only appropriate failed identifiers.' . "\n";
exit;
}
// Quiet=true means success entries need not be returned.
print 'Delete batch succeeded with no reported object errors.' . "\n";
?>