简体   繁体   中英

PHP - How can I delete a GCP bucket folder and all files/folders within it?

I'm trying to delete a folder in a GCP bucket using the gs storage PHP library.

The folder structure is like so

-Folder1
--Folder1.1
---File
---File
--Folder1.2
---File

-Folder2
--Folder2.1
---File
---File
--Folder2.3
---File

Hopefully, that makes sense. If not, I basically just need to delete a folder and all files and folders within it.

When I do

$storage->bucket($_ENV['bucket_name'])->object('folder1')->delete();

I just get a 404 "No such object" error. I can't see any additional options to use in the library to delete a folder and its contents.

You can't directly delete the folder just only using the $object->delete() function. You need to list all the object inside the folder with the use of prefix in bucket to locate specific location of your folder.. Then, delete it one by one because the API only supports deleting a single object at a time. It means, there is no API call to delete multiple objects using wildcards or the like clause.

To delete all files including the folder use the sample code below, inspired from this answer :

require __DIR__ . '/vendor/autoload.php';

use Google\Cloud\Storage\StorageClient;

function delete_Folder($bucketName)
{

    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $objects = $bucket->objects([
        'prefix' => 'foldername/'
    ]);
    foreach ($objects as $object) {
        $object->delete();
        printf('Deleted object: %s' . PHP_EOL, $object->name());
    }
}

delete_Folder("mybucket");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM