Criação e uso de buckets do Amazon S3 com o versão 3 AWS SDK for PHP - AWS SDK for PHP

As traduções são geradas por tradução automática. Em caso de conflito entre o conteúdo da tradução e da versão original em inglês, a versão em inglês prevalecerá.

Criação e uso de buckets do Amazon S3 com o versão 3 AWS SDK for PHP

Os exemplos a seguir mostram como:

  • Retorne uma lista de buckets pertencentes ao remetente autenticado da solicitação usando. ListBuckets

  • Crie um novo bucket usando CreateBucketo.

  • Adicione um objeto a um bucket usando PutObject.

Todo o código de exemplo para o AWS SDK for PHP está disponível aqui em GitHub.

Credenciais

Antes de executar o código de exemplo, configure suas credenciais da AWS, conforme descrito em Credenciais. Em seguida, importe o AWS SDK for PHP, conforme descrito em Uso básico.

Importações

require 'vendor/autoload.php'; use Aws\S3\S3Client;

Listar buckets

Crie um arquivo PHP com o seguinte código. Primeiro crie um serviço cliente do AWS.S3 que especifique a região e a versão da AWS. Depois, chame o método listBuckets, que retorna todos os buckets do Amazon S3 pertencentes ao remetente da solicitação como uma matriz de estruturas de bucket.

Código de exemplo

$s3Client = new S3Client([ 'profile' => 'default', 'region' => 'us-west-2', 'version' => '2006-03-01' ]); //Listing all S3 Bucket $buckets = $s3Client->listBuckets(); foreach ($buckets['Buckets'] as $bucket) { echo $bucket['Name'] . "\n"; }

Criar um bucket

Crie um arquivo PHP com o seguinte código. Primeiro crie um serviço cliente do AWS.S3 que especifique a região e a versão da AWS. Em seguida, chame o método createBucket com uma matriz como o parâmetro. O único campo obrigatório é a chave "Bucket", com um valor de string para o nome do bucket a ser criado. No entanto, você pode especificar a AWS região com o campo CreateBucketConfiguration ''. Se for bem-sucedido, esse método retornará o “Local” do bucket.

Código de exemplo

function createBucket($s3Client, $bucketName) { try { $result = $s3Client->createBucket([ 'Bucket' => $bucketName, ]); return 'The bucket\'s location is: ' . $result['Location'] . '. ' . 'The bucket\'s effective URI is: ' . $result['@metadata']['effectiveUri']; } catch (AwsException $e) { return 'Error: ' . $e->getAwsErrorMessage(); } } function createTheBucket() { $s3Client = new S3Client([ 'profile' => 'default', 'region' => 'us-east-1', 'version' => '2006-03-01' ]); echo createBucket($s3Client, 'my-bucket'); } // Uncomment the following line to run this code in an AWS account. // createTheBucket();

Colocar um objeto em um bucket

Para adicionar arquivos ao novo bucket, crie um arquivo PHP com o código a seguir.

Na linha de comando, execute esse arquivo e passe o nome do bucket no qual você deseja fazer upload do arquivo como uma sequência, seguido pelo caminho completo para o arquivo cujo upload você deseja fazer.

Código de exemplo

$USAGE = "\n" . "To run this example, supply the name of an S3 bucket and a file to\n" . "upload to it.\n" . "\n" . "Ex: php PutObject.php <bucketname> <filename>\n"; if (count($argv) <= 2) { echo $USAGE; exit(); } $bucket = $argv[1]; $file_Path = $argv[2]; $key = basename($argv[2]); try { //Create a S3Client $s3Client = new S3Client([ 'profile' => 'default', 'region' => 'us-west-2', 'version' => '2006-03-01' ]); $result = $s3Client->putObject([ 'Bucket' => $bucket, 'Key' => $key, 'SourceFile' => $file_Path, ]); } catch (S3Exception $e) { echo $e->getMessage() . "\n"; }