简体   繁体   中英

Upload to AWS S3 with AWS PHP SDK fails authentication

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() . "\n";
}

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM