4

I'm trying to download an object from AWS S3 using the SDK for PHP.

$filename = "filename with spaces in it.jpg";

$src = "path/from/bucket-root/".$filename;

$result = S3Client->getObject([

    'Bucket' => 'my-bucket-name',
    'Key' => $src
]);

When I run this, I get an error:

Error executing "GetObject" ... GET filename%20with%20spaces%20in%20it.jpg resulted in a 404 Not Found response:

The S3 client is encoding the spaces but then not able to resolve the path.

Ive tried all of the following:

$filename = urlencode("filename with spaces in it.jpg");
$filename = urldecode("filename with spaces in it.jpg");
$filename = addslashes("filename with spaces in it.jpg");
$filename = str_replace(' ','+',"filename with spaces in it.jpg");

And several combinations - Im just throwing turds at the wall at this point.

My key path and bucket name/route are correct since I am able to successfully get object without spaces in the filename.

How do I grab this object with spaces in the filename?

yevg
  • 1,846
  • 9
  • 34
  • 70

1 Answers1

1

It actually works without replacing spaces with anything, here is the working code

<?php
require 'aws/aws-autoloader.php';
use Aws\S3\S3Client;
use Aws\S3\Exception\S3Exception;

$bucket = 'avitest29oct2018';
$keyname = 'hello there.txt';

$s3 = new S3Client([
  'version' => 'latest',
  'region'  => 'us-west-2',
  'credentials' => false
]);

try {
  // Get the object.
  $result = $s3->getObject([
    'Bucket' => $bucket,
    'Key'    => $keyname
  ]);

  // Display the object in the browser.
  header("Content-Type: {$result['ContentType']}");
  echo $result['Body'];
} catch (S3Exception $e) {
   echo $e->getMessage() . PHP_EOL;
}

?>

Note:-

  1. Remove credentials' => false to read private S3 file
  2. I will take down my the S3 file in few days, replace bucket name and keyname in the above code

Not sure if it is related to the aws sdk you used, there are various ways you can install aws sdk for php, how did you install it? i used 3rd method (using zip file)

avinash
  • 523
  • 1
  • 5
  • 10