Search code examples
phpamazon-s3php-5.5aws-php-sdk

Upload to s3 via PHP fails access denied


I feel a bit stupid to ask this, but is there anything special required to upload something via the current PHP SDK to S3? I can upload via the cli with the same credentials, but when I try the SDK it fails.

Here the code:

<?php
require "awssdk_v3/aws-autoloader.php";

use Aws\S3\S3Client;

function s3_upload($file, $name) {
    $s3 = S3Client::factory(
        array(
            'key' => getenv('AWS_ACCESS_KEY_ID'),
            'secret' => getenv('AWS_SECRET_ACCESS_KEY'),
            'version' => "2006-03-01",
            'region' => getenv('AWS_REGION')
        )
    );
    $result = $s3->putObject(
        array(
            'Bucket' => getenv('AWS_BUCKET'),
            'Key' => $name,
            'SourceFile' => $file,
            'ContentType' => mime_content_type($file),
            'ACL' => 'public-read'
        )
    );
    return true;
}

I call it like this

s3_upload($_FILES['avatarfile']['tmp_name'], "avatar_2.jpg");

The user I use has this policy attached:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "Stmt1480066717000",
            "Effect": "Allow",
            "Action": [
                "s3:DeleteObject",
                "s3:GetObject",
                "s3:PutObject"
            ],
            "Resource": [
                "arn:aws:s3:::my-bucket/*"
            ]
        },
        {
            "Sid": "Stmt1480066765000",
            "Effect": "Allow",
            "Action": [
                "s3:ListBucket"
            ],
            "Resource": [
                "arn:aws:s3:::my-bucket"
            ]
        }
    ]
}

As mentioned I was able to upload a file from the CLI using that users credentials. The region is Frankfurt, so I specified eu-central-1, correct?

The error I get starts like this:

Fatal error: Uncaught exception 'Aws\S3\Exception\S3Exception' with message 'Error executing "PutObject" on "https://my-bucket.s3.eu-central-1.amazonaws.com/avatar_2.jpg"; AWS HTTP error: Client error: `PUT https://my-bucket.s3.eu-central-1.amazonaws.com/avatar_2.jpg` resulted in a `403 Forbidden` response

Solution

  • I found the problem thanks to this answer. I'm trying to set the ACL 'public-read', but haven't granted myself s3:PutObjectAcl, just s3:PutObject. Changing either fixes the problem.

    Thanks anyway for the help.