Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a folder within S3 bucket using PHP

I'm trying to create a folder within an S3 amazon bucket but I'm finding it difficult to find the right documentation to adequately explain what is needed. I have the following code / pseudocode for creating a folder. Can anyone explain or provide a sample of the arguments I need to place within the code

use vendor\aws\S3\S3Client;

$bucket_url = 'https://***.amazonaws.com/***/';
$folder_name = $username . '/';

$s3Client = new vendor\aws\S3\S3Client([
        'version' => AWS_VERSION,
        'region' => AWS_REGION,
        'credentials' => [
            'key' => AWS_KEY,
            'secret' =>AWS_SECRET,
        ],
    ]);

    $s3Client->putObject(array(
        'Bucket' => AWS_BUCKET, // Defines name of Bucket
        'Key' => AWS_PATH . $folder_name, //Defines Folder name
        'Body' => "",
    ));
like image 748
KPM Avatar asked Mar 26 '26 16:03

KPM


2 Answers

S3 doesn't have folders beyond the bucket, but objects (files) can have /s (forward slashes) in their name, and there are methods to retrieve based on a prefix that allows you to emulate a directory-list. This means though, that you can't create an empty folder.

So a work around will be put a empty txt file and delete it after wards but the folder structure will stay.

/* function to upload empty test.txt file to subfolders /folder/ on S3 bucketname */
$s3->putObjectFile(‘test.txt’, ‘bucketname’, ‘/folder/test.txt’, S3::ACL_PUBLIC_READ);

/* function to delete empty test.txt file to subfolders /folder/ on S3 bucketname */
$s3->deleteObject(‘bucketname’, ‘/folder/test.txt’);
like image 128
error2007s Avatar answered Mar 28 '26 07:03

error2007s


Amazon S3 does not have a concept of folders. For S3, all objects are simply a key name with data.

Folders are a human concept which use the '/' character to separate the folders. But S3 does not care.

When you use many third-party tools (and even the AWS Management Console), the tools often will look at the object keys under your prefix and when it sees a '/' in it, it will interpret it as a folder.

But there's no way to "create a folder".

If you you simply PutObject an object with a key with your desired full path (for example, "my/desired/folder/structure/file.txt"), Amazon S3 will put it there. It's not like many filesystems where the folder must exist before a file can be created.

The closest thing to "creating a folder" you could do is to create a 0-byte object with a '/' at the end of it's key. For example "my/desired/folder/structure/". But it will just be another object in the bucket. It won't have any effect on the creation or operation of the bucket or any other objects in the bucket.

like image 39
Matt Houser Avatar answered Mar 28 '26 05:03

Matt Houser