I am trying to delete _$folder$ from Google Storage using their REST api. I have tried so far headerserver.com/testestset/*, headerserver.com/testestset, headerserver.com/testestset_$folder$ but neither seem to work when there are any files in the folder.
The only approach I came up so far is to foreach all objects under the _$folder$ before attempting to delete it, however, this is highly inefficient.
In a worst scenario: is it possible to batch/delete more than one file per one request?
It's been 4 years, and they still don't give a proper API for this.
For you who still need a work around, here is an option.
This example is to remove a parent folder, its nested folders, and all of their contents
<?php
/**
* Delete nested folders for Google Cloud Storage
*/
class ClassName {
/** @var Google_Service_Storage $storageService */
public $storageService;
/** @var string $bucket */
public $bucket = '';
/**
* Remove an object
*
* @param string $objectPath
* @return boolean
*/
public function removeObject($objectPath) {
// validator
try {
if (!$this->storageService->objects->get($this->bucket, $objectPath)) {
// log error
return false;
}
} catch (Exception $ex) {
// leave this empty
}
// remove action
try {
$this->storageService->objects->delete($this->bucket, $objectPath);
} catch (Exception $ex) {
// log error
return false;
}
// log success
return true;
}
/**
* Remove the specified container
*
* @param string $path
* @return boolean
*/
public function removeContainer($path) {
$c = array();
$c['delimiter'] = '/';
if (!empty($path) && $path != '/') {
$c['prefix'] = $path;
}
$objects = null;
// validator
try {
$objects = $this->storageService->objects->listObjects($this->bucket, $c);
if (empty($objects)) {
if (!$this->storageService->objects->get($this->bucket, $path)) {
// log error
return false;
}
}
} catch (Exception $ex) {
// leave this empty
}
// remove action
try {
if (empty($objects)) {
$this->storageService->objects->delete($this->bucket, $path);
} else {
/**
* Process files first
*/
$files = $objects->getItems();
if (!empty($files)) {
foreach ($files as $file) {
$this->removeObject($file->getName());
}
}
/**
* And folders later
*/
$folders = $objects->getPrefixes();
if (!empty($folders)) {
foreach ($folders as $folder) {
$this->removeContainer($folder);
}
}
}
} catch (Exception $ex) {
// log error
return false;
}
// log success
return true;
}
}
This is how it's logged in database, to explain the recursive process.

If you are curious why empty-folders came out twice in the log for file_remove and directory_remove, this $objects = $this->driver->objects->listObjects($this->bucket, $c); part listed the folder's name back into $files = $objects->getItems();,
may be because it's not a physical folder, but rather an empty file that represents as a folder.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With