Search code examples
phpgoogle-apigoogle-drive-apigoogle-api-php-client

Delete folder if no files exist within it - Google Drive API


I currently have the function:

function deleteFileUsingID($fileID) {
    $this->service->files->delete($fileID);
}

How would I have to modify it such that after deleting the file, if no files exists within that folder, it deletes the folder itself.


Solution

  • I believe your goal as follows.

    • When there are no files in the specific folder, you want to delete the folder.

    In this case, you can check whether the files are in the folder using the method of "Files: list" in Drive API.

    Modified script:

    Please set the folder ID to $folderId = '###';.

    function deleteFileUsingID($fileID) {
        $this->service->files->delete($fileID);
    
        $folderId = '###';  // Please set the folder ID.
        $fileList = $this->service->files->listFiles(array("q" => "'{$folderId}' in parents"));
        if (count($fileList->getFiles()) == 0) {
            $this->service->files->delete($folderId);
        }
    }
    

    Or, when you want to retrieve the folder ID from $fileID, you can also use the following script.

    function deleteFileUsingID($fileID) {
        $folderIds = $this->service->files->get($fileID, array("fields" => "parents"))->getParents();
    
        $this->service->files->delete($fileID);
    
        if (count($folderIds) > 0) {
            $folderId = $folderIds[0];
            $fileList = $this->service->files->listFiles(array("q" => "'{$folderId}' in parents"));
            if (count($fileList->getFiles()) == 0) {
                $this->service->files->delete($folderId);
            }
        }
    }
    
    • In this modified script, after $this->service->files->delete($fileID); was run, it checks whether the files are in the folder using the method of "Files: list". When no files in the folder, the folder is deleted.

    Note:

    • In this case, the folder is deleted. So please be careful this. I would like to recommend to use the sample folder for testing the script.

    Reference: