1

PHP/AWS S3 rookie here: working on a project where I need to be able to display both an album artwork from AWS S3 bucket as well as play a music file. I can upload, but when trying to view image, it downloads instead. Have checked the content-type and content disposition. I believe the problem is around this snippet of code: I would appreciate any help/suggestions.

<?php
....
....
try {
$s3 = S3Client::factory(
  array(
    'credentials' => array(
      'key' => $IAM_KEY,
      'secret' => $IAM_SECRET
    ),
    'version' => 'latest',
    'region'  => 'us-east-2'
  )
);
//
$result = $s3->getObject(array(
  'Bucket' => $BUCKET_NAME,
  'Key'    => $keyPath
));
echo $result;
//exit();
// Display it in the browser
header("Content-Type: {$result['ContentType']}");
header('Content-Disposition: filename="' . basename($keyPath) . '"');
return $result['Body'];
} catch (Exception $e) {
   die("Error: " . $e->getMessage());
}
?>
<!DOCTYPE html>
<html>
  <head>
    <title>display image</title>
 </head>
 <body>
   <img src="<?php echo $result['body']; ?>">
 </body>
</html>
Reza Mousavi
  • 4,420
  • 5
  • 31
  • 48
Bonaii
  • 75
  • 6
  • have you tried `file_get_contents()`? Does your bucket have view permissions for all that's not your auth user? – Joshua Oct 08 '18 at 00:43
  • Yes i have @Joshua but it no good. i can get to the bucket and access the content but instead of displaying it on my browser, it downloads it to my desktop – Bonaii Oct 08 '18 at 00:59
  • @Bonsa side note, you're doing this the hard way, downloading the contents onto the server and returning them to the browser, which requires server resources unnecessarily. You can just generate a pre-signed URL with a short expiration and redirect the browser to it, allowing the browser to fetch directly from S3 with authorization provided by the signed URL. – Michael - sqlbot Oct 08 '18 at 10:53
  • Also, `echo $result;` seems problematic. Doesn't that send the result object to the browser? (My php is a little rusty.) You say *"Have checked the content-type and content disposition"* -- where did you check them? In the response headers the browser sees? Why are you returning a `Content-Disposition`? What should be unnecessary, and possibly unhelpful, when trying to view and not download the object. – Michael - sqlbot Oct 08 '18 at 10:58

1 Answers1

0

Quoted/Stolen from this answer:

You can download the contents from S3 (in a PHP script), then serve them using the correct headers.

As a rough example, say you had the following in image.php:

$s3 = new AmazonS3();
$response = $s3->get_object($bucket, $image_name);
if (!$response->isOK()) {
    throw new Exception('Error downloading file from S3');
}
header("Content-Type: image/jpeg");
header("Content-Length: " . strlen($response->body));
die($response->body);
Then in your HTML code, you can do

<img src="image.php">
Joshua
  • 1,128
  • 3
  • 17
  • 31