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

google drive file.list query returns false for sub-folder ID - php


I'm able to list the items present in a folder located in root of google drive using the following function. but when I try to list items in a sub-folder located inside a parent folder (parent folder is in root of google drive)

[PARENT FOLDER] //the 'sub folder' and 'other files' are getting listed
       └------[SUB FOLDER] //query is returned false when i try to put this folder ID as parent
       |            └--------[FILE LOCATED INSIDE SUB FOLDER]
       └------[OTHER FILES]

Function used to list files from google drive:


function listFilesFolders($client, $search, $subFolderId){

        $service = new Google_Service_Drive($client);

        //ID of the folder located in root of google drive
        //works fine if i run the query with this ID
        $superParentId = '1Xky058b134vadgSOyD-ADFagaGAGAdgha'; 

        //properly working query
        //$query = "'".$superParentId."' in parents and trashed = false"; 

        //query that runs for the subfolder located inside the parent folder ($superParentId)
        $query = "'".$subFolderId."' in parents and trashed = false"; 

        $optParams = array('q' => $query);

        // Returns the list of files and folders as object
        $results = $service->files->listFiles($optParams);

        // Return false if nothing is found
        if (count($results->getFiles()) == 0) {
            return false;
        }

        // Converting array to object
        $result = array();
        foreach ($results->getFiles() as $file) {
            $result[$file->getId()] = $file->getName();
        }

        return $result;
}

May I know how to list files located in the sub folder?

Thanks,


Solution

  • You need to do two things

    1. Find out which of the files in your super parent folder are subfolders You can do it with a modified query:
    $query2 = "'$superParentId' in parents and trashed = false and mimeType='application/vnd.google-apps.folder'";
    ... 
    
    1. List the files contained in those subfolders in a loop
    ...
    $query3 = "'$subFolderId' in parents and trashed = false";
    ...