0

I have this code below that should upload an image to my s3 bucket but I don't know how to tell it to upload to a specific folder (named videouploads) in my s3 bucket. Can anyone help?

require 'vendor/autoload.php';

use Aws\S3\S3Client;

// Instantiate an Amazon S3 client.
$s3 = new S3Client([
    'version' => 'latest',
    'region'  => 'grabage',
    'credentials' => [
        'key'    => 'garbage',
        'secret' => 'grabage'
    ]
]);


$bucketName = 'cgrabage';
$file_Path = __DIR__ . '/my-image.png';
$key = basename($file_Path);

// Upload a publicly accessible file. The file size and type are determined by the SDK.
try {
    $result = $s3->putObject([
        'Bucket' => $bucketName,
        'Key'    => $key,
        'Body'   => fopen($file_Path, 'r'),
        'ACL'    => 'public-read',
    ]);
    echo $result->get('ObjectURL');
} catch (Aws\S3\Exception\S3Exception $e) {
    echo "There was an error uploading the file.\n";
    echo $e->getMessage();
}
  • 1
    Does this answer your question? [PutObject into directory Amazon s3 / PHP](https://stackoverflow.com/questions/24665062/putobject-into-directory-amazon-s3-php) – Jeff Vdovjak Jan 30 '20 at 04:04
  • yes that somewhat does answer my question but now I'm getting that error stating `an error uploading the file. Error executing "PutObject" on "https://cactustestphp.s3.us west.amazonaws.com/videouploads/my-image.png"; AWS HTTP error: cURL error 3: (see https://curl.haxx.se/libcurl/c/libcurl-errors.html)` –  Jan 30 '20 at 04:20

1 Answers1

2

You need to put the directory information in the key.

$result = $s3->putObject([
    'Bucket' => $bucketName,
    'Key'    => 'videouploads/' . $key,
    'Body'   => fopen($file_Path, 'r'),
    'ACL'    => 'public-read',
]);
Jeff Vdovjak
  • 1,833
  • 16
  • 21
  • For some reason everytime I try to run the code, theres an error saying: There was `an error uploading the file. Error executing "PutObject" on "https://cactustestphp.s3.us west.amazonaws.com/videouploads/my-image.png"; AWS HTTP error: cURL error 3: (see https://curl.haxx.se/libcurl/c/libcurl-errors.html)` It says incorrect url, but what exactly does that mean? Are my keys wrong? –  Jan 30 '20 at 04:16
  • Nevermind I know how to to fix my issue. However your asnwer is correct, thanks! –  Jan 30 '20 at 04:42
  • I'm glad you found your solution :) – Jeff Vdovjak Jan 30 '20 at 12:42