i have this working code to delete files and folders from s3. how would you delete using wildcard * ?
$s3 = new AmazonS3();
$bucket = 'mybucket';
$folder = 'myDirectory/*';// this doesnt work
$response = $s3->get_object_list($bucket, array(
'prefix' => $folder
));
foreach ($response as $v) {
$s3->delete_object($bucket, $v);
}
Presumably using wildcard * means you want to delete all objects at once rather than one at a time?
This is possible via delete_all_objects($bucket, $pcre), where $pcreis an optional Perl-Compatible Regular Expression (PCRE) to filter the names against (default is PCRE_ALL, which is "/.*/i"), e.g.:
$s3 = new AmazonS3();
$response = $s3->delete_all_objects($bucket, "#myDirectory/.*#");
I've chosen # rather than the usual / as the pattern enclosing delimiter to avoid escaping (not a problem with the single slash here, but it get's messy soon for more complex cases), see Delimiters for details.
Please note that deleting multiple objects had not been possible in the past at the Amazon S3 API level and simulated in the AWS SDK for PHP with a for loop within delete_all_objects() as well, i.e. it used one request per object still; fortunately, Amazon has finally introduced Amazon S3 - Multi-Object Delete in December 2011:
Amazon S3's new Multi-Object Delete gives you the ability to delete up to 1000 objects from an S3 bucket with a single request.
Support for S3 Multi Object Delete has been added to the AWS SDK for PHP shortly thereafter accordingly, see AWS SDK for PHP 1.4.8 "Zanarkand":
The AmazonS3 class now allows you to delete multiple Amazon S3 objects using a single HTTP request. This has been exposed as the delete_objects() method, and the delete_all_objects() and delete_all_object_versions() methods have been rewritten to leverage this new Amazon S3 feature.
An example for a dedicated multi-object delete (i.e. without wildcards) is shown as well:
$s3 = new AmazonS3();
$response = $s3->delete_objects($bucket, array(
'objects' => array(
array('Key' => 'file1.txt'),
array('Key' => 'file2.txt'),
)
));
Here is how to delete by prefix (as close to wildcard as I have gotten).
call like: _delete_by_prefix_amazon('pdfs/1-')
/**
* Delete files by folder and prefix for Amazon
*
* Deletes files from a service based on a prefix.
* For Amazon prefix must contain folder.
*
* @access public
* @param string prefix
* @return mixed response from service api
*/
function _delete_by_prefix_amazon($prefix = ''){
$s3 = new AmazonS3($credentials);
$objects = $s3->get_object_list($bucket, array('prefix' => $prefix));
$delete = array('objects'=>array());
foreach ($objects as $object)
{
$delete['objects'][]['key'] = (string)$object;
}
//debug($delete);
return $s3->delete_objects($this->bucket, $delete);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With