如何通过PHP访问AWS S3 ?


How do I access AWS S3 via PHP?

我已经按照这里的入门说明使用Composer安装了用于PHP的AWS SDK。我把它安装在我的html根目录下。我创建了一个名为"ImageUser"的IAM用户,其唯一权限为"AmazonS3FullAccess",并捕获了其密钥。

根据这里的说明,我创建了一个名为"credentials"的文件,如下所示:

[default]
aws_access_key_id = YOUR_AWS_ACCESS_KEY_ID
aws_secret_access_key = YOUR_AWS_SECRET_ACCESS_KEY

是的,我用适当的键替换了那些大写的单词。该文件位于"隐藏子目录"中。HTML根目录中的"Aws"。文件的UNIX权限是664。

我创建了这个简单的文件(名为"test.php"在我的html根目录名为"t"的子目录中)来测试上传文件到S3:

<?php
// Include the AWS SDK using the Composer autoloader.
require '../vendor/autoload.php';
use Aws'S3'S3Client;
use Aws'S3'Exception'S3Exception;
$bucket = 'testbucket';
$keyname = 'test.txt';
// Instantiate the client.
$s3 = S3Client::factory();
try {
    // Upload data.
    $result = $s3->putObject(array(
        'Bucket' => $bucket,
        'Key'    => $keyname,
        'Body'   => 'Hello, world!',
        'ACL'    => 'public-read'
    ));
    // Print the URL to the object.
    echo $result['ObjectURL'] . "'n";
} catch (S3Exception $e) {
    echo $e->getMessage() . "'n";
}
?>

不幸的是,它抛出了一个http错误500行:

$s3 = S3Client::factory();

是的,自动加载器目录是正确的。是的,桶存在。不,test.txt文件不存在。

根据上面提到的页面,"如果没有向SDK显式提供凭据或配置文件,并且没有在环境变量中定义凭据,但是定义了凭据文件,SDK将使用'默认'配置文件。"即使如此,我也尝试在工厂语句中显式指定配置文件"default",只是为了得到相同的结果。

我做错了什么?

;您有多个AWS SDK版本

  • 根据你在邮件中提供的链接(链接),你已经安装了php sdk v3
  • 根据您的示例,您使用PHP sdk v2

v3不知道S3Client::factory方法,所以这就是它抛出错误的原因。您可以继续检查链接以查看使用情况https://docs.aws.amazon.com/aws-sdk-php/v3/guide/getting-started/basic-usage.html。有几种方法可以获取s3客户机

  1. 创建客户端-简单方法

    <?php
    // Include the SDK using the Composer autoloader
    require 'vendor/autoload.php';
    $s3 = new Aws'S3'S3Client([
        'version' => 'latest',
        'region'  => 'us-east-1'
    ]);
    
  2. 创建客户端-使用sdk类

    // Use the us-west-2 region and latest version of each client.
    $sharedConfig = [
        'region'  => 'us-west-2',
        'version' => 'latest'
    ];
    // Create an SDK class used to share configuration across clients.
    $sdk = new Aws'Sdk($sharedConfig);
    // Create an Amazon S3 client using the shared configuration data.
    $s3 = $sdk->createS3();
    

一旦你有了你的客户端,你可以使用你现有的代码(是的,这个是v3)在s3上放一个新对象,所以你会得到像

这样的东西
<?php
// Include the AWS SDK using the Composer autoloader.
require '../vendor/autoload.php';
use Aws'S3'S3Client;
use Aws'S3'Exception'S3Exception;
$bucket = 'testbucket';
$keyname = 'test.txt';
// Instantiate the client.
-- select method 1 or 2 --
try {
    // Upload data.
    $result = $s3->putObject(array(
        'Bucket' => $bucket,
        'Key'    => $keyname,
        'Body'   => 'Hello, world!',
        'ACL'    => 'public-read'
    ));
    // Print the URL to the object.
    echo $result['ObjectURL'] . "'n";
} catch (S3Exception $e) {
    echo $e->getMessage() . "'n";
}