AMAZON S3 DOWNLOAD A PRIVATE FILE AND SHOW IT IN WEB BROWSER IN PHP.

Dhruvil Gala
3 min readNov 1, 2019

--

Recently I have been working with a project where AWS came into the picture. I needed to upload a file and to download also from the s3 bucket. Now here was the main task to read the file from S3 private bucket.

For eg. ,I uploaded a file in a private S3 bucket, and now I wanted to show it in the image view in PHP. There Code available on AWS docs but I wasn’t able to figure out how to implement it. after some struggle, I was able to do the fetching thing.

In this blog, I will show you how to download a file from a private S3 bucket and also how to read a file from a private S3 bucket in PHP.

DOWNLOADING A FILE FROM S3 PRIVATE BUCKET:-

The following code is for downloading the file from an S3 bucket that has an IAM role. Just put the credentials in the blank spaces and you just good to go. The file will be downloaded.

FETCHING A FILE FROM S3 PRIVATE BUCKET AND VIEWING IT IN BROWSER:-

The following code is for fetching the file from an S3 bucket that has an IAM role. Same instructions as above, enter your credentials and you are good to go.

Here in the code, while fetching the file from the S3 bucket which has an IAM role is not possible directly. So to get the URL of the image which has the access to be viewed can be created from this code. AWS has a built-in function called createPresignedRequest(). Now all this function does is creates a URL of the required file which is in private S3 bucket.

Now it takes two parameters accordingly,

  1. The S3 client object information ($command as per code),
  2. And the second parameter is the time limit given to the URL (+6 days as per the code above).

The time limit can be as you can configure means. it can be either, 10 minutes, 1 hour, 1 day, +6days. You can give the time limit more than +6 days as per AWS terms. so make sure you give the correct time and if given beyond the limit it will throw an error of exceeding the time for presigned URL.

Conclusion

Just copy the code as per your requirement, put up your credentials and see them working.

for any queries, you can just visit the official documentation by AWS from the below link.

If you liked this article, please show your appreciation by clapping 👏 below!

Did I get something wrong? Mention it in the comments.
I would love to improve.

I hope you enjoyed this post. I will also come up with some more blogs.
Have a Nice Day.✌️

--

--