Aws s3 copy and replicate folder in laravel

Viewed 5400

I am trying to copy a folder which is already on s3 and save it with different name on S3 in laravel 5.4 . What I have found so far is that I can copy an Image, Not folder. I have tried to copy folder like ie:

 $disk->copy("admin/form/$old_form","admin/form/$new_form");

But it doesnot work like that. It give me an error. Do i need to apply loop and get each folder item separately? Like:

$images = $disk->allFiles('admin/form/$id');

Or is there any work around available in laravel or s3 api it self?

Please help, Its driving me crazy.

Thanks in advance.

4 Answers

Another option:

$files = Storage::disk('s3')->allFiles("old/location");
foreach($files as $file){
   $copied_file = str_replace("old/location", "new/location", $file);
   if(!Storage::disk('s3')->exists($copied_file)) Storage::disk('s3')->copy($file, $copied_file);
}

This can all be done from CLI:

Install and configure s3cmd:

sudo apt install s3cmd
s3cmd --configure

Then you can:

s3cmd sync --delete-removed path/to/folder s3://bucket-name/path/to/folder/

To make the files and folder public:

s3cmd setacl s3://bucket-name/path/to/folder/ --acl-public --recursive

Further reading: https://s3tools.org/s3cmd-sync

I've found a faster way to do this is by utilizing aws command line tools, specifically the aws s3 sync command.

Once installed on your system, you can invoke from within your Laravel project using shell_exec - example:

$source = 's3://abc';
$destination = 's3://xyz';
shell_exec('aws s3 sync ' . $source . ' ' . $destination);

If your set your AWS_KEY and AWS_SECRET in your .env file, the aws command will refer to these values when invoked from within Laravel.

Related