使用适用于 PHP 的 SDK 的 Amazon S3 示例 - Amazon SDK for PHP
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅 中国的 Amazon Web Services 服务入门 (PDF)

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

使用适用于 PHP 的 SDK 的 Amazon S3 示例

以下代码示例向您展示了如何在 Amazon S3 中使用来执行操作和实现常见场景。 Amazon SDK for PHP

操作是大型程序的代码摘录,必须在上下文中运行。您可以通过操作了解如何调用单个服务函数,还可以通过函数相关场景和跨服务示例的上下文查看操作。

场景是展示如何通过在同一服务中调用多个函数来完成特定任务任务的代码示例。

每个示例都包含一个指向的链接 GitHub,您可以在其中找到有关如何在上下文中设置和运行代码的说明。

开始使用

以下代码示例展示了如何开始使用 Amazon S3。

适用于 PHP 的 SDK
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整实例,了解如何进行设置和运行。

use Aws\S3\S3Client; $client = new S3Client(['region' => 'us-west-2']); $results = $client->listBuckets(); var_dump($results);
  • 有关 API 的详细信息,请参阅 Amazon SDK for PHP API 参考ListBuckets中的。

操作

以下代码示例演示如何使用 CopyObject

适用于 PHP 的 SDK
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整实例,了解如何进行设置和运行。

对象的简单副本。

$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 的详细信息,请参阅 Amazon SDK for PHP API 参考CopyObject中的。

以下代码示例演示如何使用 CreateBucket

适用于 PHP 的 SDK
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整实例,了解如何进行设置和运行。

创建存储桶。

$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 的详细信息,请参阅 Amazon SDK for PHP API 参考CreateBucket中的。

以下代码示例演示如何使用 DeleteBucket

适用于 PHP 的 SDK
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整实例,了解如何进行设置和运行。

删除空桶。

$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 的详细信息,请参阅 Amazon SDK for PHP API 参考DeleteBucket中的。

以下代码示例演示如何使用 DeleteObjects

适用于 PHP 的 SDK
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整实例,了解如何进行设置和运行。

从键列表中删除一组对象。

$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 的详细信息,请参阅 Amazon SDK for PHP API 参考DeleteObjects中的。

以下代码示例演示如何使用 GetObject

适用于 PHP 的 SDK
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整实例,了解如何进行设置和运行。

获取对象。

$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 的详细信息,请参阅 Amazon SDK for PHP API 参考GetObject中的。

以下代码示例演示如何使用 ListObjectsV2

适用于 PHP 的 SDK
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整实例,了解如何进行设置和运行。

列出存储桶中的对象。

$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 的详细信息,请参阅 Amazon SDK for PHP API 参考中的 ListObjectsV2

以下代码示例演示如何使用 PutObject

适用于 PHP 的 SDK
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整实例,了解如何进行设置和运行。

将对象上传到存储桶。

$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 的详细信息,请参阅 Amazon SDK for PHP API 参考PutObject中的。

场景

以下代码示例展示了如何为 Amazon S3 创建预签名 URL 以及如何上传对象。

适用于 PHP 的 SDK
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整实例,了解如何进行设置和运行。

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
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

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 = "doc-example-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";

无服务器示例

以下代码示例展示了如何实现一个 Lambda 函数,该函数接收通过将对象上传到 S3 桶而触发的事件。该函数从事件参数中检索 S3 存储桶名称和对象密钥,并调用 Amazon S3 API 来检索和记录对象的内容类型。

适用于 PHP 的 SDK
注意

还有更多相关信息 GitHub。在无服务器示例存储库中查找完整示例,并了解如何进行设置和运行。

通过 PHP 将 S3 事件与 Lambda 结合使用。

// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 <?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);