【问题标题】:Basic AWS S3 PHP setup基本 AWS S3 PHP 设置
【发布时间】:2016-04-29 21:08:07
【问题描述】:

我一直在尝试设置一个上传表单的基本 PHP 实现以上传到 Amazon 的 S3 服务,但我什么也做不了。

阅读他们的文档,他们的示例似乎都不同。 提供凭据和上传文件的正确方法是什么?

在他们的 github repo 上,它说:

// Require the Composer autoloader.
require 'vendor/autoload.php';

use Aws\S3\S3Client;

// Instantiate an Amazon S3 client.
$s3 = new S3Client([
    'version' => 'latest',
    'region'  => 'us-west-2'
]);

try {
    $s3->putObject([
        'Bucket' => 'my-bucket',
        'Key'    => 'my-object',
        'Body'   => fopen('/path/to/file', 'r'),
        'ACL'    => 'public-read',
    ]);
} catch (Aws\Exception\S3Exception $e) {
    echo "There was an error uploading the file.\n";
}

http://docs.aws.amazon.com/aws-sdk-php/v2/guide/service-s3.html 他们说:

use Aws\S3\S3Client;

$client = S3Client::factory(array(
    'profile' => '<profile in your aws credentials file>'
));

// Upload an object by streaming the contents of a file
// $pathToFile should be absolute path to a file on disk
$result = $client->putObject(array(
    'Bucket'     => $bucket,
    'Key'        => 'data_from_file.txt',
    'SourceFile' => $pathToFile,
    'Metadata'   => array(
        'Foo' => 'abc',
        'Baz' => '123'
    )
));

// We can poll the object until it is accessible
$client->waitUntil('ObjectExists', array(
    'Bucket' => $this->bucket,
    'Key'    => 'data_from_file.txt'
));

最近能够做到这一点的任何人都可以解释一下这里的设置吗?

【问题讨论】:

标签: php amazon-web-services amazon-s3 amazon


【解决方案1】:

您链接到的文档中的关键是这句话:

您可以像前面的示例一样提供您的凭据配置文件, 直接指定您的访问密钥(通过密钥和秘密),或者您可以 如果您使用的是 AWS,请选择省略任何凭证信息 EC2 实例的身份和访问管理 (IAM) 角色

因此,如果您从 EC2 实例运行此程序,您只需忽略任何凭据,它应该从与实例关联的角色中获取权限。

如果您不在 AWS 中运行,则需要为运行代码的用户创建 ~/.aws/config,并创建一个类似于

的配置文件
[profile profile_name]
aws_access_key_id = key
aws_secret_access_key = secret
region = us-east-1

那么你就这样做:

$client = S3Client::factory(array(
  'profile' => 'profile_name'
));

【讨论】:

    【解决方案2】:

    我最终通过使用嵌入的凭据让它工作

    <?php
    
    date_default_timezone_set("America/Denver");
    
    require "./aws/aws-autoloader.php";
    
    use Aws\S3\S3Client;
    
    $s3Client = S3Client::factory(array(
        'credentials' => array(
            'key'    => 'key',
            'secret' => 'secret',
        ),
        "region" => "us-east-1",
        "version" => "latest"
    ));
    
    ?>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-23
      • 2017-11-19
      • 1970-01-01
      • 1970-01-01
      • 2017-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多