[英]Delete folder in Amazon S3 using PHP
我刚开始尝试使用 Amazon S3 来托管我网站的图像。 我正在使用官方 Amazon AWS PHP SDK 库。
问题:如何删除位于 S3“文件夹”中的所有文件?
例如,如果我有一个名为images/2012/photo.jpg
的文件,我想删除所有文件名以images/2012/
开头的文件。
从 S3 中删除文件夹及其所有文件的最佳方法是使用 API deleteMatchingObjects()
$s3 = S3Client::factory(...);
$s3->deleteMatchingObjects('YOUR_BUCKET_NAME', '/some/dir');
S3 没有“文件夹”,因为您在文件系统上通常认为它们是(一些 S3 客户端只是做得很好,使 S3看起来有文件夹)。 这些/
实际上是文件名的一部分。
因此,API 中没有“删除文件夹”选项。 您只需要删除具有images/2012/...
前缀的每个单独文件。
更新:
这可以通过 Amazon S3 PHP 客户端中的delete_all_objects
方法来完成。 只需在第二个参数中指定"/^images\\/2012\\//"
作为正则表达式前缀(第一个参数是您的存储桶名称)。
我已经测试过了,它可以工作 2019-05-28
function Amazon_s3_delete_dir($delPath, $s3, $bucket) {
//the $dir is the path to the directory including the directory
// the directories need to have a / at the end.
// Clear it just in case it may or may not be there and then add it back in.
$dir = rtrim($dir, "/");
$dir = ltrim($dir, "/");
$dir = $dir . "/";
$response = $s3->getIterator(
'ListObjects',
[
'Bucket' => $bucket,
'Prefix' => $delPath
]
);
//delete each
foreach ($response as $object) {
$fileName = $object['Key'];
$s3->deleteObject([
'Bucket' => $bucket,
'Key' => $fileName
]);
}//foreach
return true;
}//function
用法:
$delPath = $myDir . $theFolderName . "/";
Amazon_s3_delete_dir($delPath, $s3, $bucket);
$s3 = new Aws\S3\Client([ 'region' => 'us-west-2', 'version' => 'latest' ]);
$listObjectsParams = ['Bucket' => 'foo', 'Prefix' => 'starts/with/'];
// Asynchronously delete
$delete = Aws\S3\BatchDelete::fromListObjects($s3, $listObjectsParams);
// Force synchronous completion $delete->delete();
$promise = $delete->promise();
这是一个可以做你想做的事情的函数。
/**
* This function will delete a directory. It first needs to look up all objects with the specified directory
* and then delete the objects.
*/
function Amazon_s3_delete_dir($dir){
$s3 = new AmazonS3();
//the $dir is the path to the directory including the directory
// the directories need to have a / at the end.
// Clear it just in case it may or may not be there and then add it back in.
$dir = rtrim($dir, "/");
$dir = ltrim($dir, "/");
$dir = $dir . "/";
//get list of directories
$response = $s3->get_object_list(YOUR_A3_BUCKET, array(
'prefix' => $dir
));
//delete each
foreach ($response as $v) {
$s3->delete_object(YOUR_A3_BUCKET, $v);
}//foreach
return true;
}//function
用途:如果我想删除目录foo
Amazon_s3_delete_dir("path/to/directory/foo/");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.