codernoob8
codernoob8

Reputation: 712

Delete folder that contains files from s3 bucket php

Im trying to delete a folder in an s3 bucket that is located in a folder called CreativeEngine the folder structure looks like this CreativeEngine/8943 I want to delete the folder with the called 8943 but it contains files within it. Do I need to do some kind of loop to delete the files first or can I delete the folder? I tried this but it didn't work

    <?php 
$itemId=$_GET['id'];
    require('s3/vendor/autoload.php');
        use Aws\S3\S3Client;
        use Aws\S3\Exception\S3Exception;
        // AWS Info
        $bucketName = 'mybucket';
        $IAM_KEY = 'mykey';
        $IAM_SECRET = 'mysecret';
        // Connect to AWS
            $s3 = S3Client::factory(
                array(
                    'credentials' => array(
                        'key' => $IAM_KEY,
                        'secret' => $IAM_SECRET
                    ),
                    'version' => 'latest',
                    'region'  => 'us-east-2'
                )
            );


    $s3Destination='CreativeEngine/'.$itemId;
    $keyName = $s3Destination;

    try{
    $s3->deleteObject(array(
        'Bucket' => $bucketName,
        'Key'    => $keyName
    ));       
    } catch (S3Exception $e) {
    $data['message']='<li>error'.$e->getMessage().'</li>';
    }
    ?>

Upvotes: 1

Views: 1575

Answers (1)

CFL_Jeff
CFL_Jeff

Reputation: 2719

This is possible via delete_all_objects($bucket, $pcre), where $pcreis an optional Perl-Compatible Regular Expression (PCRE) to filter the names against (default is PCRE_ALL, which is "/.*/i"), e.g.:

$s3 = new AmazonS3();
$response = $s3->delete_all_objects($bucket, "#myDirectory/.*#");

Upvotes: 1

Related Questions