简体   繁体   中英

How do I download a file from a signed URL from Amazon S3 to a client machine using PHP?

When a user clicks a link on the site, I'm trying to download a file from an Amazon S3 bucket with a signed URL through php. Here's what I have so far:

$client = S3Client::factory(
    array(
      'key' => 'xyz',
      'secret' => 'abc'
));

$signedUrl = $client->getObjectUrl(<bucket>, $location, '+10 minutes');

Now, how do I download the file using the above signed url to client machine?

Assuming that you are having problems only in fetching the url and have implemented api properly, this should work

$client = S3Client::factory(
    array(
      'key' => 'xyz',
      'secret' => 'abc'
));

$signedUrl = $client->getObjectUrl(<bucket>, $location, '+10 minutes');
file_put_contents($fileName, file_get_contents($signedUrl));

Now this puts the file on your server. In order to download to client there are a couple of methods. Let me try with the most simplest

header('Content-Type: application/csv'); // Change mime type
header('Content-Disposition: attachment; filename=temp.csv'); // Change filename
header('Pragma: no-cache');
echo (file_get_contents($signedUrl));

This would rather than saving on server serve the output to client. Another alternative would be you send the url to javascript and download from client side.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM