SDK で を使用する Amazon S3 の例 PHP - AWS SDK コード例

AWS Doc SDK Examples GitHub リポジトリには他にも AWS SDK例があります。

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

SDK で を使用する Amazon S3 の例 PHP

次のコード例は、Amazon S3 AWS SDK for PHP で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

「基本」は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

アクションはより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

「シナリオ」は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には、完全なソースコードへのリンクが含まれています。ここでは、コンテキストでコードを設定および実行する方法の手順を確認できます。

開始方法

次のコード例は、Amazon S3 の使用を開始する方法を示しています。

PHP に関する SDK
注記

の詳細については、「」を参照してください GitHub。用例一覧を検索し、AWS コード例リポジトリでの設定と実行の方法を確認してください。

use Aws\S3\S3Client; $client = new S3Client(['region' => 'us-west-2']); $results = $client->listBuckets(); var_dump($results);
  • API 詳細については、 リファレンスListBucketsの「」を参照してください。 AWS SDK for PHP API

基本

次のコードサンプルは、以下の操作方法を示しています。

  • バケットを作成し、そこにファイルをアップロードします。

  • バケットからオブジェクトをダウンロードします。

  • バケット内のサブフォルダにオブジェクトをコピーします。

  • バケット内のオブジェクトを一覧表示します。

  • バケットオブジェクトとバケットを削除します。

PHP に関する SDK
注記

の詳細については、「」を参照してください GitHub。用例一覧を検索し、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";

アクション

次のコード例は、CopyObject を使用する方法を示しています。

PHP に関する SDK
注記

の詳細については、「」を参照してください GitHub。用例一覧を検索し、AWS コード例リポジトリでの設定と実行の方法を確認してください。

オブジェクトの単純なコピー。

$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."); }
  • API 詳細については、 リファレンスCopyObjectの「」を参照してください。 AWS SDK for PHP API

次のコード例は、CreateBucket を使用する方法を示しています。

PHP に関する SDK
注記

の詳細については、「」を参照してください GitHub。用例一覧を検索し、AWS コード例リポジトリでの設定と実行の方法を確認してください。

バケットを作成します。

$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."); }
  • API 詳細については、 リファレンスCreateBucketの「」を参照してください。 AWS SDK for PHP API

次の例は、DeleteBucket を使用する方法を説明しています。

PHP に関する SDK
注記

の詳細については、「」を参照してください GitHub。用例一覧を検索し、AWS コード例リポジトリでの設定と実行の方法を確認してください。

空のバケットを削除します。

$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."); }
  • API 詳細については、 リファレンスDeleteBucketの「」を参照してください。 AWS SDK for PHP API

次のコード例は、DeleteObjects を使用する方法を示しています。

PHP に関する SDK
注記

の詳細については、「」を参照してください GitHub。用例一覧を検索し、AWS コード例リポジトリでの設定と実行の方法を確認してください。

キーのリストからオブジェクトのセットを削除します。

$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."); }
  • API 詳細については、 リファレンスDeleteObjectsの「」を参照してください。 AWS SDK for PHP API

次のコード例は、GetObject を使用する方法を示しています。

PHP に関する SDK
注記

の詳細については、「」を参照してください GitHub。用例一覧を検索し、AWS コード例リポジトリでの設定と実行の方法を確認してください。

オブジェクトを取得します。

$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."); }
  • API 詳細については、 リファレンスGetObjectの「」を参照してください。 AWS SDK for PHP API

次のコード例は、ListObjectsV2 を使用する方法を示しています。

PHP に関する SDK
注記

の詳細については、「」を参照してください GitHub。用例一覧を検索し、AWS コード例リポジトリでの設定と実行の方法を確認してください。

バケット内のオブジェクトを一覧表示します。

$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."); }
  • API 詳細については、 AWS SDK for PHP APIリファレンスListObjectsV2 を参照してください。

次のコード例は、PutObject を使用する方法を示しています。

PHP に関する SDK
注記

の詳細については、「」を参照してください GitHub。用例一覧を検索し、AWS コード例リポジトリでの設定と実行の方法を確認してください。

オブジェクトをバケットにアップロードします。

$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."); }
  • API 詳細については、 リファレンスPutObjectの「」を参照してください。 AWS SDK for PHP API

シナリオ

次のコード例は、Amazon S3 URL用の署名付き を作成し、オブジェクトをアップロードする方法を示しています。

PHP に関する SDK
注記

の詳細については、「」を参照してください GitHub。用例一覧を検索し、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();

次のコード例では、ユーザーがラベルを使用して写真を管理できるサーバーレスアプリケーションを作成する方法について示しています。

PHP に関する SDK

Amazon Rekognition を使用して画像内のラベルを検出し、保存して後で取得できるようにする写真アセット管理アプリケーションの開発方法を示します。

完全なソースコードと、セットアップと実行の手順については、 GitHub「」の詳細な例を参照してください。

この例のソースについて詳しくは、AWS  コミュニティでブログ投稿を参照してください。

この例で使用されているサービス
  • API ゲートウェイ

  • DynamoDB

  • Lambda

  • Amazon Rekognition

  • Amazon S3

  • Amazon SNS

サーバーレスサンプル

次のコード例は、S3 バケットにオブジェクトをアップロードすることによってトリガーされるイベントを受け取る Lambda 関数を実装する方法を示しています。この関数は、イベントパラメータから S3 バケット名とオブジェクトキーを取得し、Amazon S3 を呼び出しAPIてオブジェクトのコンテンツタイプを取得およびログに記録します。

PHP に関する SDK
注記

の詳細については、「」を参照してください GitHub。サーバーレスサンプルリポジトリで完全な例を検索し、設定および実行の方法を確認してください。

を使用して Lambda で S3 イベントを消費するPHP。

<?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);