phpamazon-web-servicesamazon-s3create-directory

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' => "",
    ));

Solution

  • 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’);