문제

I created a new amazon bucket called "photos". The bucket url is something like:

www.amazons3.salcaiser.com/photos

Now I upload subfolders containing files, into that bucket for example

www.amazons3.salcaiser.com/photos/thumbs/file.jpg

My questions are, does thumbs/ is assumed a new bucket or is it an object?

Then if I want to delete the entire thumbs/ directory need I first to delete all files inside that or can I delete all in one time?

도움이 되었습니까?

해결책

In the case you are describing, "photos" is the bucket. S3 does not have sub-buckets or directories. Directories are simulated by using slashes in the object key. "thumbs/file.jpg" is an object key and "thumbs/" would be considered a key prefix.

Dagon's examples are good and use the older version 1.x of the AWS SDK for PHP. However, you can do this more easily with the newest 2.4.x version AWS SDK for PHP which includes a helper method for deleting multiple objects.

<?php

// Include the SDK. This line depends on your installation method.
require 'aws.phar';

use Aws\S3\S3Client;

$s3 = S3Client::factory(array(
    'key'    => 'your-aws-access-key',
    'secret' => 'your-aws-secret-key',
));

// Delete the objects in the "photos" bucket with the a prefix of "thumbs/"
$s3->deleteMatchingObjects('photos', 'thumbs/');

다른 팁

//Include s3.php file first in code

if (!class_exists('S3'))
            require_once('S3.php');
        //AWS access info
        if (!defined('awsAccessKey'))
            define('awsAccessKey', 'awsAccessKey');
        if (!defined('awsSecretKey'))
            define('awsSecretKey', 'awsSecretKey');
        //instantiate the class
        $s3 = new S3(awsAccessKey, awsSecretKey);

  if ($s3->deleteObject("bucketname", `filename`)) {
        echo 'deleted';
}
else
{
echo 'no file found';
}

found some code snippets for 'directory' deletion - i did not write them:

PHP 5.3+:

$s3 = new AmazonS3();

$bucket = 'your-bucket';
$folder = 'folder/sub-folder/';

$s3->get_object_list($bucket, array(
    'prefix' => $folder
))->each(function($node, $i, $s3) {
    $s3->batch()->delete_object($bucket, $node);
}, array($s3));
$responses = $s3->batch()->send();

var_dump($responses->areOK());

Older PHP 5.2.x:

$s3 = new AmazonS3();


$bucket = 'your-bucket';
$folder = 'folder/sub-folder/';

$s3->get_object_list($bucket, array(
    'prefix' => $folder
))->each('construct_batch_delete', array($s3));

function construct_batch_delete($node, $i, &$s3)
{
    $s3->batch()->delete_object($bucket, $node);
}

$responses = $s3->batch()->send();

var_dump($responses->areOK());

I have implemented this in Yii as,

$aws = Yii::$app->awssdk->getAwsSdk();
$s3 = $aws->createS3();
$s3->deleteMatchingObjects('Bucket Name','object key');
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top