dozxos6346
dozxos6346
2018-09-08 23:44

使用AWS PHP SDK上传到AWS S3无法通过身份验证

已采纳

I am using version 3.67.5 of AWS SDK PHP to upload files to S3. The code is in an Heroku dyno.

I've created the access keys, AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY, and set them as configuration variables in the Heroku instance. I know that they are there, because with getenv() I 've outputted them.

I'm using the following code:

try {
   //Create a S3Client
   $s3Client = new S3Client([
        'profile' => 'default',
        'region' => 'some-region',
        'version' => 'latest'
    ]);
    $result = $s3Client->putObject([
        'Bucket'     => 'some-bucket',
        'Key'        => $fileName,
        'SourceFile' => $this->getParameter('photos_directory') . $fileName,
    ]);
} catch (AwsException $e) {
    echo $e->getMessage() . "
";
}

Still, uploading a file, it shows the following error:

request.CRITICAL: Uncaught PHP Exception Aws\Exception\CredentialsException: "Cannot read credentials from /app/.aws/credentials"

I've tested passing a new element 'credentials' in the constructor, like they do in theirs unit tests, and the error is the same.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

2条回答

  • dongri1989 dongri1989 3年前

    The problem was in defining the profile as "default". When I removed the profile parameter, the error disappeared.

    When using the latest version, 3.67.8, the following error occurred:

    AWS HTTP error: Client error: `PUT https: // some-url` resulted in a` 403 Forbidden`
    

    Anyway, in my case, and in both versions, omitting the profile parameter was the solution.

    点赞 评论 复制链接分享
  • dongyizhui0616 dongyizhui0616 3年前

    Step 1: Make sure that the file /app/.aws/credentials does not exist. If it does exist and is empty, your will have a credentials error.

    Step 2: Change your client code to the following:

    use Aws\Credentials\CredentialProvider;
    
    $s3Client = new S3Client([
         'profile' => 'default',
         'region' => 'some-region',
         'version' => 'latest',
         credentials' => CredentialProvider::env()
    ]);
    

    If this does not solve your problem, then either you have mispelled the environment variables or they are not exported so that your program can see them.

    If this does work, then there are invalid credentials somewhere else.

    点赞 评论 复制链接分享

为你推荐