Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I show an image from my Amazon S3 on my website?

I have my pictures on Amazon S3. The pictures are private and not public so I can not show them with a direct link s3.amazonaws/bucket_name/key_name/image_name.jpg

I know the image names on Amazon S3. How do I show for example the Amazon S3 images flower.png and house.png on my website with PHP?

like image 979
Xtreme Avatar asked Jan 04 '15 18:01

Xtreme


1 Answers

For those who needs this behavior with AWS SDK v3, if you directly call getObjectUrl with '+10 minutes' as third parameter, it will always return the plain URL. That's because the method changed. To get the pre-signed link, do the following:

//Get an instance of S3 Client. This is one one to do it:
$s3Client = new S3Client([
    'version'     => 'latest',
    'region'      => 'us-west-2', //Region of the bucket
    'credentials' => array(
        'key' => 'YOUR-ACCOUNT-KEY',
        'secret'  => 'YOUR-ACCOUNT-SECRET',
    )
]);

//Get a command to GetObject
$cmd = $s3Client->getCommand('GetObject', [
    'Bucket' => 'YOUR-BUCKET-NAME',
    'Key'    => 'YOUR-FILE-KEY'
]);

//The period of availability
$request = $s3Client->createPresignedRequest($cmd, '+10 minutes');

//Get the pre-signed URL
$signedUrl = (string) $request->getUri();

Ref: https://docs.aws.amazon.com/aws-sdk-php/v3/guide/service/s3-presigned-url.html

like image 104
Laerte Avatar answered Oct 14 '22 10:10

Laerte