Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a file public that is uploaded to Amazon s3

I'm following this tutorial to upload files to amazon s3 from php. The tutorial is very good, but I have a small problem, all the uploaded files have to be made public manually to be able to see them from the internet. Is there any way to automate this?

upload.php

<?php 
    // This file demonstrates file upload to an S3 bucket. This is for using file upload via a
    // file compared to just having the link. If you are doing it via link, refer to this:
    // https://gist.github.com/keithweaver/08c1ab13b0cc47d0b8528f4bc318b49a
    //
    // You must setup your bucket to have the proper permissions. To learn how to do this
    // refer to:
    // https://github.com/keithweaver/python-aws-s3
    // https://www.youtube.com/watch?v=v33Kl-Kx30o

    // I will be using composer to install the needed AWS packages.
    // The PHP SDK:
    // https://github.com/aws/aws-sdk-php
    // https://packagist.org/packages/aws/aws-sdk-php 
    //
    // Run:$ composer require aws/aws-sdk-php
    require 'libs/aws-autoloader.php';

    use Aws\S3\S3Client;
    use Aws\S3\Exception\S3Exception;
    // AWS Info
    $bucketName = 'test.com.mx';
    $IAM_KEY = 'XXXXXX';
    $IAM_SECRET = 'XXXXXXXX';
    // Connect to AWS
    try {
        // You may need to change the region. It will say in the URL when the bucket is open
        // and on creation.
        $s3 = S3Client::factory(
            array(
                'credentials' => array(
                    'key' => $IAM_KEY,
                    'secret' => $IAM_SECRET
                ),
                'version' => 'latest',
                'region'  => 'us-west-2'
            )
        );
    } catch (Exception $e) {
        // We use a die, so if this fails. It stops here. Typically this is a REST call so this would
        // return a json object.
        die("Error: " . $e->getMessage());
    }

    // For this, I would generate a unqiue random string for the key name. But you can do whatever.
    $keyName = 'test_example/' . basename($_FILES["fileToUpload"]['name']);
    $pathInS3 = 'https://s3.us-east-2.amazonaws.com/' . $bucketName . '/' . $keyName;
    // Add it to S3
    try {
        // Uploaded:
        $file = $_FILES["fileToUpload"]['tmp_name'];
        $s3->putObject(
            array(
                'Bucket'=>$bucketName,
                'Key' =>  $keyName,
                'SourceFile' => $file,
                'ContentType' => 'image/png',
            )
        );
    } catch (S3Exception $e) {
        die('Error:' . $e->getMessage());
    } catch (Exception $e) {
        die('Error:' . $e->getMessage());
    }
    echo 'Done';
    // Now that you have it working, I recommend adding some checks on the files.
    // Example: Max size, allowed file types, etc.





 ?>

Bucket Policy

{
    "Version": "2012-10-17",
    "Id": "Policy1488494182833",
    "Statement": [
        {
            "Sid": "Stmt1488493308547",
            "Effect": "Allow",
            "Principal": {
                "AWS": "arn:aws:iam::281979644754:user/sample-user"
            },
            "Action": [
                "s3:ListBucket",
                "s3:ListBucketVersions",
                "s3:GetBucketLocation",
                "s3:Get*",
                "s3:Put*"
            ],
            "Resource": "arn:aws:s3:::img-bucket-00123"
        }
    ]
}

CORS CONNFIGURATION

<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
  <CORSRule>
    <AllowedOrigin>*</AllowedOrigin>
    <AllowedMethod>GET</AllowedMethod>
    <AllowedMethod>POST</AllowedMethod>
    <AllowedMethod>PUT</AllowedMethod>
    <MaxAgeSeconds>3000</MaxAgeSeconds>
    <AllowedHeader>Authorization</AllowedHeader>
  </CORSRule>
</CORSConfiguration>

enter image description here

enter image description here

enter image description here

enter image description here

enter image description here

Tutorial: https://github.com/keithweaver/python-aws-s3

Thank you.

like image 368
Neftali Acosta Avatar asked Mar 06 '23 07:03

Neftali Acosta


1 Answers

If you wish to make all the contents on an Amazon S3 bucket (or a specific path within the bucket) publicly accessible, then this is easiest by using a Bucket Policy such as:

{
    "Version": "2012-10-17",
    "Id": "MakePublic",
    "Statement": [
        {
            "Sid": "MakePublic",
            "Effect": "Allow",
            "Principal": "*",
            "Action": [
                "s3:GetObject"
            ],
            "Resource": "arn:aws:s3:::img-bucket-00123/*"
        }
    ]
}

This way, you will not need to assign permissions to each individual object. Any object in that bucket will be publicly accessible.

Note the /* at the end of the bucket name.

like image 88
John Rotenstein Avatar answered Mar 07 '23 23:03

John Rotenstein