php-awsHow do I delete a file from an Amazon S3 bucket using PHP?
To delete a file from an Amazon S3 bucket using PHP, you can use the deleteObject
method of the AWS SDK for PHP. The following example code shows how to delete a file from a bucket.
// Include the SDK using the Composer autoloader
require 'vendor/autoload.php';
// Instantiate the S3 client with your AWS credentials
$s3Client = new Aws\S3\S3Client([
'region' => 'us-east-1',
'version' => 'latest',
'credentials' => [
'key' => 'YOUR_AWS_ACCESS_KEY_ID',
'secret' => 'YOUR_AWS_SECRET_ACCESS_KEY',
],
]);
// Delete the file from the bucket
$result = $s3Client->deleteObject([
'Bucket' => 'my-bucket',
'Key' => 'my-file.txt',
]);
// Print the result
print_r($result);
The output of the above code would look like this:
Aws\Result Object
(
[data:Aws\Result:private] => Array
(
[DeleteMarker] =>
[VersionId] =>
[RequestCharged] =>
[ResponseMetadata] => Array
(
[RequestId] => xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
[HostId] =>
)
)
)
The code can be broken down into the following parts:
- Include the SDK using the Composer autoloader:
require 'vendor/autoload.php';
- Instantiate the S3 client with your AWS credentials:
$s3Client = new Aws\S3\S3Client([...])
- Delete the file from the bucket:
$result = $s3Client->deleteObject([...])
- Print the result:
print_r($result);
For more information, please refer to the AWS SDK for PHP documentation.
More of Php Aws
- How can I use PHP to create an asynchronous application on AWS?
- How do I use PHP to create a ZIP file on AWS?
- How can I use AWS and Zksync together with PHP?
- How can I use Yum to install PHP on an Amazon EC2 instance?
- How can I use an AWS SQS Worker with PHP?
- How can I use AWS WAF to secure my PHP application?
- How can I use AWS PHP SDK without credentials?
- How do I generate an AWS Signature Version 4 with PHP?
- How do I determine the version of PHP I am running on AWS?
- How can I use the AWS S3 S3Client library with PHP?
See more codes...