如果桶不存在则创建桶

vee*_*er7 2 php amazon-s3

我想检查是否存在特定的存储桶,如果不存在则创建新的存储桶。

我需要知道如何使用 aws.phar + php 检测存储桶是否已经存在

这是伪代码

$bucket = 'my-bucket';

//some code to detect if bucket name 'my-bucket' exists *suggest here*
//$myBucketExists = $client->someMethode()

if(!$myBucketExists){

      $result = $client->createBucket(array(
         'Bucket' => $bucket
      ));

      // Wait until the bucket is created
      $client->waitUntil('BucketExists', array('Bucket' => $bucket));
}
// rest of the code using the bucket
Run Code Online (Sandbox Code Playgroud)

Nad*_*adh 5

使用headBucket()

$myBucketExists = $client->headBucket( array('Bucket' => $bucket) );
Run Code Online (Sandbox Code Playgroud)

  • 当我使用 $client->doesBucketExist($bucket); 即使存储桶存在,它也会返回 false。有谁知道我做错了什么? (4认同)
  • 还有一个 [doesBucketExists()](http://docs.aws.amazon.com/aws-sdk-php-2/latest/class-Aws.S3.S3Client.html#_doesBucketExist) 使用 headBucket 的辅助方法。 (2认同)
  • 使用 headBucket() 方法,我必须编写在 catch 块中创建新存储桶的代码,因为如果存储桶不存在,headBucket 将抛出异常。这样就可以工作了。谢谢@Nadh (2认同)