PHP Extension AWS S3: Delete File from an S3 Bucket

Back to Index

Demonstrates how to delete a file from an S3 bucket. This example deletes the file /chilkat.ocean/starfishCopy.jpg. A response status code equal to 204 is returned for success (with an empty response body).

Documentation: https://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectDELETE.html

CURL Command

curl -X DELETE https://chilkat.ocean.s3.us-west-2.amazonaws.com/starfishCopy.jpg

PHP Extension Example

<?php

// The version number (9_5_0) should match version of the Chilkat extension used, omitting the micro-version number.
// For example, if using Chilkat v9.5.0.48, then include as shown here:
include("chilkat_9_5_0.php");

$rest = new CkRest();

$authAws = new CkAuthAws();
$authAws->put_AccessKey('AWS_ACCESS_KEY');
$authAws->put_SecretKey('AWS_SECRET_KEY');
$authAws->put_Region('us-west-2');
$authAws->put_ServiceName('s3');
$rest->SetAuthAws($authAws);

//  URL: https://chilkat.ocean.s3.us-west-2.amazonaws.com/starfishCopy.jpg
$bTls = true;
$port = 443;
$bAutoReconnect = true;
$success = $rest->Connect('chilkat.ocean.s3.us-west-2.amazonaws.com',$port,$bTls,$bAutoReconnect);
if ($success != true) {
    print 'ConnectFailReason: ' . $rest->get_ConnectFailReason() . "\n";
    print $rest->lastErrorText() . "\n";
    exit;
}

$sbResponseBody = new CkStringBuilder();
$success = $rest->FullRequestNoBodySb('DELETE','/starfishCopy.jpg',$sbResponseBody);
if ($success != true) {
    print $rest->lastErrorText() . "\n";
    exit;
}

$respStatusCode = $rest->get_ResponseStatusCode();
if ($respStatusCode >= 400) {
    print 'Response Status Code = ' . $respStatusCode . "\n";
    print 'Response Header:' . "\n";
    print $rest->responseHeader() . "\n";
    print 'Response Body:' . "\n";
    print $sbResponseBody->getAsString() . "\n";
    exit;
}


?>