Contoh Amazon S3 menggunakan for SDK PHP - AWS SDKContoh Kode

Ada lebih banyak AWS SDK contoh yang tersedia di GitHub repo SDKContoh AWS Dokumen.

Terjemahan disediakan oleh mesin penerjemah. Jika konten terjemahan yang diberikan bertentangan dengan versi bahasa Inggris aslinya, utamakan versi bahasa Inggris.

Contoh Amazon S3 menggunakan for SDK PHP

Contoh kode berikut menunjukkan cara melakukan tindakan dan menerapkan skenario umum dengan menggunakan Amazon S3. AWS SDK for PHP

Dasar-dasar adalah contoh kode yang menunjukkan kepada Anda bagaimana melakukan operasi penting dalam suatu layanan.

Tindakan adalah kutipan kode dari program yang lebih besar dan harus dijalankan dalam konteks. Sementara tindakan menunjukkan cara memanggil fungsi layanan individual, Anda dapat melihat tindakan dalam konteks dalam skenario terkait.

Skenario adalah contoh kode yang menunjukkan kepada Anda bagaimana menyelesaikan tugas tertentu dengan memanggil beberapa fungsi dalam layanan atau dikombinasikan dengan yang lain Layanan AWS.

Setiap contoh menyertakan tautan ke kode sumber lengkap, di mana Anda dapat menemukan instruksi tentang cara mengatur dan menjalankan kode dalam konteks.

Memulai

Contoh kode berikut ini menunjukkan cara memulai menggunakan Amazon S3.

SDKuntuk PHP
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode AWS.

use Aws\S3\S3Client; $client = new S3Client(['region' => 'us-west-2']); $results = $client->listBuckets(); var_dump($results);
  • Untuk API detailnya, lihat ListBucketsdi AWS SDK for PHP APIReferensi.

Hal-hal mendasar

Contoh kode berikut ini menunjukkan cara:

  • Membuat bucket dan mengunggah file ke dalamnya.

  • Mengunduh objek dari bucket.

  • Menyalin objek ke subfolder di bucket.

  • Membuat daftar objek dalam bucket.

  • Menghapus objek bucket dan bucket tersebut.

SDKuntuk PHP
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode AWS.

echo("\n"); echo("--------------------------------------\n"); print("Welcome to the Amazon S3 getting started demo using PHP!\n"); echo("--------------------------------------\n"); $region = 'us-west-2'; $this->s3client = new S3Client([ 'region' => $region, ]); /* Inline declaration example $s3client = new Aws\S3\S3Client(['region' => 'us-west-2']); */ $this->bucketName = "amzn-s3-demo-bucket-" . uniqid(); try { $this->s3client->createBucket([ 'Bucket' => $this->bucketName, 'CreateBucketConfiguration' => ['LocationConstraint' => $region], ]); echo "Created bucket named: $this->bucketName \n"; } catch (Exception $exception) { echo "Failed to create bucket $this->bucketName with error: " . $exception->getMessage(); exit("Please fix error with bucket creation before continuing."); } $fileName = __DIR__ . "/local-file-" . uniqid(); try { $this->s3client->putObject([ 'Bucket' => $this->bucketName, 'Key' => $fileName, 'SourceFile' => __DIR__ . '/testfile.txt' ]); echo "Uploaded $fileName to $this->bucketName.\n"; } catch (Exception $exception) { echo "Failed to upload $fileName with error: " . $exception->getMessage(); exit("Please fix error with file upload before continuing."); } try { $file = $this->s3client->getObject([ 'Bucket' => $this->bucketName, 'Key' => $fileName, ]); $body = $file->get('Body'); $body->rewind(); echo "Downloaded the file and it begins with: {$body->read(26)}.\n"; } catch (Exception $exception) { echo "Failed to download $fileName from $this->bucketName with error: " . $exception->getMessage(); exit("Please fix error with file downloading before continuing."); } try { $folder = "copied-folder"; $this->s3client->copyObject([ 'Bucket' => $this->bucketName, 'CopySource' => "$this->bucketName/$fileName", 'Key' => "$folder/$fileName-copy", ]); echo "Copied $fileName to $folder/$fileName-copy.\n"; } catch (Exception $exception) { echo "Failed to copy $fileName with error: " . $exception->getMessage(); exit("Please fix error with object copying before continuing."); } try { $contents = $this->s3client->listObjectsV2([ 'Bucket' => $this->bucketName, ]); echo "The contents of your bucket are: \n"; foreach ($contents['Contents'] as $content) { echo $content['Key'] . "\n"; } } catch (Exception $exception) { echo "Failed to list objects in $this->bucketName with error: " . $exception->getMessage(); exit("Please fix error with listing objects before continuing."); } try { $objects = []; foreach ($contents['Contents'] as $content) { $objects[] = [ 'Key' => $content['Key'], ]; } $this->s3client->deleteObjects([ 'Bucket' => $this->bucketName, 'Delete' => [ 'Objects' => $objects, ], ]); $check = $this->s3client->listObjectsV2([ 'Bucket' => $this->bucketName, ]); if (count($check) <= 0) { throw new Exception("Bucket wasn't empty."); } echo "Deleted all objects and folders from $this->bucketName.\n"; } catch (Exception $exception) { echo "Failed to delete $fileName from $this->bucketName with error: " . $exception->getMessage(); exit("Please fix error with object deletion before continuing."); } try { $this->s3client->deleteBucket([ 'Bucket' => $this->bucketName, ]); echo "Deleted bucket $this->bucketName.\n"; } catch (Exception $exception) { echo "Failed to delete $this->bucketName with error: " . $exception->getMessage(); exit("Please fix error with bucket deletion before continuing."); } echo "Successfully ran the Amazon S3 with PHP demo.\n";

Tindakan

Contoh kode berikut menunjukkan cara menggunakanCopyObject.

SDKuntuk PHP
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode AWS.

Salinan sederhana dari suatu objek.

$s3client = new Aws\S3\S3Client(['region' => 'us-west-2']); try { $folder = "copied-folder"; $this->s3client->copyObject([ 'Bucket' => $this->bucketName, 'CopySource' => "$this->bucketName/$fileName", 'Key' => "$folder/$fileName-copy", ]); echo "Copied $fileName to $folder/$fileName-copy.\n"; } catch (Exception $exception) { echo "Failed to copy $fileName with error: " . $exception->getMessage(); exit("Please fix error with object copying before continuing."); }
  • Untuk API detailnya, lihat CopyObjectdi AWS SDK for PHP APIReferensi.

Contoh kode berikut menunjukkan cara menggunakanCreateBucket.

SDKuntuk PHP
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode AWS.

Buat bucket.

$s3client = new Aws\S3\S3Client(['region' => 'us-west-2']); try { $this->s3client->createBucket([ 'Bucket' => $this->bucketName, 'CreateBucketConfiguration' => ['LocationConstraint' => $region], ]); echo "Created bucket named: $this->bucketName \n"; } catch (Exception $exception) { echo "Failed to create bucket $this->bucketName with error: " . $exception->getMessage(); exit("Please fix error with bucket creation before continuing."); }
  • Untuk API detailnya, lihat CreateBucketdi AWS SDK for PHP APIReferensi.

Contoh kode berikut menunjukkan cara menggunakanDeleteBucket.

SDKuntuk PHP
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode AWS.

Hapus bucket kosong.

$s3client = new Aws\S3\S3Client(['region' => 'us-west-2']); try { $this->s3client->deleteBucket([ 'Bucket' => $this->bucketName, ]); echo "Deleted bucket $this->bucketName.\n"; } catch (Exception $exception) { echo "Failed to delete $this->bucketName with error: " . $exception->getMessage(); exit("Please fix error with bucket deletion before continuing."); }
  • Untuk API detailnya, lihat DeleteBucketdi AWS SDK for PHP APIReferensi.

Contoh kode berikut menunjukkan cara menggunakanDeleteObject.

SDKuntuk PHP
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode AWS.

public function deleteObject(string $bucketName, string $fileName, array $args = []) { $parameters = array_merge(['Bucket' => $bucketName, 'Key' => $fileName], $args); try { $this->client->deleteObject($parameters); if ($this->verbose) { echo "Deleted the object named: $fileName from $bucketName.\n"; } } catch (AwsException $exception) { if ($this->verbose) { echo "Failed to delete $fileName from $bucketName with error: {$exception->getMessage()}\n"; echo "Please fix error with object deletion before continuing."; } throw $exception; } }
  • Untuk API detailnya, lihat DeleteObjectdi AWS SDK for PHP APIReferensi.

Contoh kode berikut menunjukkan cara menggunakanDeleteObjects.

SDKuntuk PHP
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode AWS.

Hapus satu set objek dari daftar kunci.

$s3client = new Aws\S3\S3Client(['region' => 'us-west-2']); try { $objects = []; foreach ($contents['Contents'] as $content) { $objects[] = [ 'Key' => $content['Key'], ]; } $this->s3client->deleteObjects([ 'Bucket' => $this->bucketName, 'Delete' => [ 'Objects' => $objects, ], ]); $check = $this->s3client->listObjectsV2([ 'Bucket' => $this->bucketName, ]); if (count($check) <= 0) { throw new Exception("Bucket wasn't empty."); } echo "Deleted all objects and folders from $this->bucketName.\n"; } catch (Exception $exception) { echo "Failed to delete $fileName from $this->bucketName with error: " . $exception->getMessage(); exit("Please fix error with object deletion before continuing."); }
  • Untuk API detailnya, lihat DeleteObjectsdi AWS SDK for PHP APIReferensi.

Contoh kode berikut menunjukkan cara menggunakanGetObject.

SDKuntuk PHP
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode AWS.

Dapatkan objek.

$s3client = new Aws\S3\S3Client(['region' => 'us-west-2']); try { $file = $this->s3client->getObject([ 'Bucket' => $this->bucketName, 'Key' => $fileName, ]); $body = $file->get('Body'); $body->rewind(); echo "Downloaded the file and it begins with: {$body->read(26)}.\n"; } catch (Exception $exception) { echo "Failed to download $fileName from $this->bucketName with error: " . $exception->getMessage(); exit("Please fix error with file downloading before continuing."); }
  • Untuk API detailnya, lihat GetObjectdi AWS SDK for PHP APIReferensi.

Contoh kode berikut menunjukkan cara menggunakanListObjectsV2.

SDKuntuk PHP
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode AWS.

Buat daftar objek dalam bucket.

$s3client = new Aws\S3\S3Client(['region' => 'us-west-2']); try { $contents = $this->s3client->listObjectsV2([ 'Bucket' => $this->bucketName, ]); echo "The contents of your bucket are: \n"; foreach ($contents['Contents'] as $content) { echo $content['Key'] . "\n"; } } catch (Exception $exception) { echo "Failed to list objects in $this->bucketName with error: " . $exception->getMessage(); exit("Please fix error with listing objects before continuing."); }
  • Untuk API detailnya, lihat ListObjectsV2 di AWS SDK for PHP APIReferensi.

Contoh kode berikut menunjukkan cara menggunakanPutObject.

SDKuntuk PHP
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode AWS.

Unggah objek ke bucket.

$s3client = new Aws\S3\S3Client(['region' => 'us-west-2']); $fileName = __DIR__ . "/local-file-" . uniqid(); try { $this->s3client->putObject([ 'Bucket' => $this->bucketName, 'Key' => $fileName, 'SourceFile' => __DIR__ . '/testfile.txt' ]); echo "Uploaded $fileName to $this->bucketName.\n"; } catch (Exception $exception) { echo "Failed to upload $fileName with error: " . $exception->getMessage(); exit("Please fix error with file upload before continuing."); }
  • Untuk API detailnya, lihat PutObjectdi AWS SDK for PHP APIReferensi.

Skenario

Contoh kode berikut menunjukkan cara membuat presigned URL untuk Amazon S3 dan mengunggah objek.

SDKuntuk PHP
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode AWS.

namespace S3; use Aws\Exception\AwsException; use AwsUtilities\PrintableLineBreak; use AwsUtilities\TestableReadline; use DateTime; require 'vendor/autoload.php'; class PresignedURL { use PrintableLineBreak; use TestableReadline; public function run() { $s3Service = new S3Service(); $expiration = new DateTime("+20 minutes"); $linebreak = $this->getLineBreak(); echo $linebreak; echo ("Welcome to the Amazon S3 presigned URL demo.\n"); echo $linebreak; $bucket = $this->testable_readline("First, please enter the name of the S3 bucket to use: "); $key = $this->testable_readline("Next, provide the key of an object in the given bucket: "); echo $linebreak; $command = $s3Service->getClient()->getCommand('GetObject', [ 'Bucket' => $bucket, 'Key' => $key, ]); try { $preSignedUrl = $s3Service->preSignedUrl($command, $expiration); echo "Your preSignedUrl is \n$preSignedUrl\nand will be good for the next 20 minutes.\n"; echo $linebreak; echo "Thanks for trying the Amazon S3 presigned URL demo.\n"; } catch (AwsException $exception) { echo $linebreak; echo "Something went wrong: $exception"; die(); } } } $runner = new PresignedURL(); $runner->run(); namespace S3; use Aws\CommandInterface; use Aws\Exception\AwsException; use Aws\Result; use Aws\S3\Exception\S3Exception; use Aws\S3\S3Client; use AwsUtilities\AWSServiceClass; use DateTimeInterface; class S3Service extends AWSServiceClass { protected S3Client $client; protected bool $verbose; public function __construct(S3Client $client = null, $verbose = false) { if ($client) { $this->client = $client; } else { $this->client = new S3Client([ 'version' => 'latest', 'region' => 'us-west-2', ]); } $this->verbose = $verbose; } public function setVerbose($verbose) { $this->verbose = $verbose; } public function isVerbose(): bool { return $this->verbose; } public function getClient(): S3Client { return $this->client; } public function setClient(S3Client $client) { $this->client = $client; } public function emptyAndDeleteBucket($bucketName, array $args = []) { try { $objects = $this->listAllObjects($bucketName, $args); $this->deleteObjects($bucketName, $objects, $args); if ($this->verbose) { echo "Deleted all objects and folders from $bucketName.\n"; } $this->deleteBucket($bucketName, $args); } catch (AwsException $exception) { if ($this->verbose) { echo "Failed to delete $bucketName with error: {$exception->getMessage()}\n"; echo "\nPlease fix error with bucket deletion before continuing.\n"; } throw $exception; } } public function createBucket(string $bucketName, array $args = []) { $parameters = array_merge(['Bucket' => $bucketName], $args); try { $this->client->createBucket($parameters); if ($this->verbose) { echo "Created the bucket named: $bucketName.\n"; } } catch (AwsException $exception) { if ($this->verbose) { echo "Failed to create $bucketName with error: {$exception->getMessage()}\n"; echo "Please fix error with bucket creation before continuing."; } throw $exception; } } public function putObject(string $bucketName, string $key, array $args = []) { $parameters = array_merge(['Bucket' => $bucketName, 'Key' => $key], $args); try { $this->client->putObject($parameters); if ($this->verbose) { echo "Uploaded the object named: $key to the bucket named: $bucketName.\n"; } } catch (AwsException $exception) { if ($this->verbose) { echo "Failed to create $key in $bucketName with error: {$exception->getMessage()}\n"; echo "Please fix error with object uploading before continuing."; } throw $exception; } } public function getObject(string $bucketName, string $key, array $args = []): Result { $parameters = array_merge(['Bucket' => $bucketName, 'Key' => $key], $args); try { $object = $this->client->getObject($parameters); if ($this->verbose) { echo "Downloaded the object named: $key to the bucket named: $bucketName.\n"; } } catch (AwsException $exception) { if ($this->verbose) { echo "Failed to download $key from $bucketName with error: {$exception->getMessage()}\n"; echo "Please fix error with object downloading before continuing."; } throw $exception; } return $object; } public function copyObject($bucketName, $key, $copySource, array $args = []) { $parameters = array_merge(['Bucket' => $bucketName, 'Key' => $key, "CopySource" => $copySource], $args); try { $this->client->copyObject($parameters); if ($this->verbose) { echo "Copied the object from: $copySource in $bucketName to: $key.\n"; } } catch (AwsException $exception) { if ($this->verbose) { echo "Failed to copy $copySource in $bucketName with error: {$exception->getMessage()}\n"; echo "Please fix error with object copying before continuing."; } throw $exception; } } public function listObjects(string $bucketName, $start = 0, $max = 1000, array $args = []) { $parameters = array_merge(['Bucket' => $bucketName, 'Marker' => $start, "MaxKeys" => $max], $args); try { $objects = $this->client->listObjectsV2($parameters); if ($this->verbose) { echo "Retrieved the list of objects from: $bucketName.\n"; } } catch (AwsException $exception) { if ($this->verbose) { echo "Failed to retrieve the objects from $bucketName with error: {$exception->getMessage()}\n"; echo "Please fix error with list objects before continuing."; } throw $exception; } return $objects; } public function listAllObjects($bucketName, array $args = []) { $parameters = array_merge(['Bucket' => $bucketName], $args); $contents = []; $paginator = $this->client->getPaginator("ListObjectsV2", $parameters); foreach ($paginator as $result) { if($result['KeyCount'] == 0){ break; } foreach ($result['Contents'] as $object) { $contents[] = $object; } } return $contents; } public function deleteObjects(string $bucketName, array $objects, array $args = []) { $listOfObjects = array_map( function ($object) { return ['Key' => $object]; }, array_column($objects, 'Key') ); if(!$listOfObjects){ return; } $parameters = array_merge(['Bucket' => $bucketName, 'Delete' => ['Objects' => $listOfObjects]], $args); try { $this->client->deleteObjects($parameters); if ($this->verbose) { echo "Deleted the list of objects from: $bucketName.\n"; } } catch (AwsException $exception) { if ($this->verbose) { echo "Failed to delete the list of objects from $bucketName with error: {$exception->getMessage()}\n"; echo "Please fix error with object deletion before continuing."; } throw $exception; } } public function deleteBucket(string $bucketName, array $args = []) { $parameters = array_merge(['Bucket' => $bucketName], $args); try { $this->client->deleteBucket($parameters); if ($this->verbose) { echo "Deleted the bucket named: $bucketName.\n"; } } catch (AwsException $exception) { if ($this->verbose) { echo "Failed to delete $bucketName with error: {$exception->getMessage()}\n"; echo "Please fix error with bucket deletion before continuing."; } throw $exception; } } public function deleteObject(string $bucketName, string $fileName, array $args = []) { $parameters = array_merge(['Bucket' => $bucketName, 'Key' => $fileName], $args); try { $this->client->deleteObject($parameters); if ($this->verbose) { echo "Deleted the object named: $fileName from $bucketName.\n"; } } catch (AwsException $exception) { if ($this->verbose) { echo "Failed to delete $fileName from $bucketName with error: {$exception->getMessage()}\n"; echo "Please fix error with object deletion before continuing."; } throw $exception; } } public function listBuckets(array $args = []) { try { $buckets = $this->client->listBuckets($args); if ($this->verbose) { echo "Retrieved all " . count($buckets) . "\n"; } } catch (AwsException $exception) { if ($this->verbose) { echo "Failed to retrieve bucket list with error: {$exception->getMessage()}\n"; echo "Please fix error with bucket lists before continuing."; } throw $exception; } return $buckets; } public function preSignedUrl(CommandInterface $command, DateTimeInterface|int|string $expires, array $options = []) { $request = $this->client->createPresignedRequest($command, $expires, $options); try { $presignedUrl = (string)$request->getUri(); } catch (AwsException $exception) { if ($this->verbose) { echo "Failed to create a presigned url: {$exception->getMessage()}\n"; echo "Please fix error with presigned urls before continuing."; } throw $exception; } return $presignedUrl; } public function createSession(string $bucketName) { try{ $result = $this->client->createSession([ 'Bucket' => $bucketName, ]); return $result; }catch(S3Exception $caught){ if($caught->getAwsErrorType() == "NoSuchBucket"){ echo "The specified bucket does not exist."; } throw $caught; } } }

Contoh kode berikut menunjukkan cara membuat aplikasi tanpa server yang memungkinkan pengguna mengelola foto menggunakan label.

SDKuntuk PHP

Menunjukkan cara mengembangkan aplikasi manajemen aset foto yang mendeteksi label dalam gambar menggunakan Amazon Rekognition dan menyimpannya untuk pengambilan nanti.

Untuk kode sumber lengkap dan instruksi tentang cara mengatur dan menjalankan, lihat contoh lengkapnya di GitHub.

Untuk mendalami tentang asal usul contoh ini, lihat postingan di Komunitas AWS.

Layanan yang digunakan dalam contoh ini
  • APIGerbang

  • DynamoDB

  • Lambda

  • Amazon Rekognition

  • Amazon S3

  • Amazon SNS

Contoh nirserver

Contoh kode berikut menunjukkan cara mengimplementasikan fungsi Lambda yang menerima peristiwa yang dipicu dengan mengunggah objek ke bucket S3. Fungsi ini mengambil nama bucket S3 dan kunci objek dari parameter event dan memanggil Amazon API S3 untuk mengambil dan mencatat jenis konten objek.

SDKuntuk PHP
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara mengatur dan menjalankannya di repositori contoh Nirserver.

Mengkonsumsi acara S3 dengan menggunakan PHP Lambda.

<?php use Bref\Context\Context; use Bref\Event\S3\S3Event; use Bref\Event\S3\S3Handler; use Bref\Logger\StderrLogger; require __DIR__ . '/vendor/autoload.php'; class Handler extends S3Handler { private StderrLogger $logger; public function __construct(StderrLogger $logger) { $this->logger = $logger; } public function handleS3(S3Event $event, Context $context) : void { $this->logger->info("Processing S3 records"); // Get the object from the event and show its content type $records = $event->getRecords(); foreach ($records as $record) { $bucket = $record->getBucket()->getName(); $key = urldecode($record->getObject()->getKey()); try { $fileSize = urldecode($record->getObject()->getSize()); echo "File Size: " . $fileSize . "\n"; // TODO: Implement your custom processing logic here } catch (Exception $e) { echo $e->getMessage() . "\n"; echo 'Error getting object ' . $key . ' from bucket ' . $bucket . '. Make sure they exist and your bucket is in the same region as this function.' . "\n"; throw $e; } } } } $logger = new StderrLogger(); return new Handler($logger);