PHP Amazon S3 provides access to private files via URL

I am using AWS PHP sdk to save images to S3. Files are kept confidential. Then I show the thumbnails of the images using the URL of the S3 file in my web application, but since the files are private, so the images are displayed as corrupted.

enter image description here

When the user clicks on the file name, the modal file opens to show a larger file, but the file appears to be damaged due to the same problem.

enter image description here

Now I know that there are two ways to make this work. 1. Make the files public. 2. Create pre-signed URLs for the files. But I can not use either of these two options due to the requirements of my project.

My question is, is there any third way to solve this problem?

0
source share
3 answers

I would really advise against this, but you could create a script on your own server that pulls the image through the API, caches it and serves it. You can then restrict access as you like without making the images publicly available.

An example goes through a script:

$headers = get_headers($realpath); // Real path being where ever the file really is foreach($headers as $header) { header($header); } $filename = $version->getFilename(); // These lines if it a download you want to do // header('Content-Description: File Transfer'); // header("Content-Disposition: attachment; filename={$filename}"); $file = fopen($realpath, 'r'); fpassthru($file); fclose($file); exit; 

This will barely β€œtouch the sides” and should not delay your files too much, but you still need to take some resources and bandwidth.

+2
source

You will need to access the files through a script on your server. That the script will do some authentication to make sure the request is valid and you want them to see the file. Then extract the file from S3 using a valid IAM profile that can access private files. File output

Instead of requesting a file with S3, request it from http://www.yourdomain.com/fetchimages.php?key=8498439834

Then here is some pseudo code in fetchimages.php

 <?php //if authorized to get this image $key=$_GET['key']; //validate key is the proper format //get s3 url from a database based on the $key //connect to s3 securely and read the file from s3 //output the file ?> 
+1
source

as far as I know, you could try to make your S3 bucket a "web server" like this , but then you will probably make the files public. Then, if you have some kind of logic to restrict access, you can create a bucket policy

0
source

Source: https://habr.com/ru/post/981173/


All Articles