Downloading from Google Drive including Sub-Directories files

Hello,

Using the code written by @katsry to create sub-directories in Google Drive, I upload directories to Google Drive, including sub-directories and files, with the following codes:

Upload the file to the specified directory

function insertFile($service, $parentId, $filename) {
    $file = new Google_Service_Drive_DriveFile();
    $file->setName(basename($filename));
    $file->setMimeType(mime_content_type($filename));
    $parentId = !empty($parentId) ? $parentId : null;
    $file->setParents(array($parentId));
    try {
        $data = file_get_contents($filename);
        $createdFile = $service->files->create($file, array(
        'data' => $data,
        'mimeType' => mime_content_type($filename),
        ));
        // Uncomment the following line to print the File ID
        // print 'File ID: %s' % $createdFile->getId();
        return $createdFile->getName();
    } catch (Exception $e) {
        print "An error occurred: " . $e->getMessage();
    }
}

Function to check whether the directory or file uploaded in Google Drive exists

function dir_exists($fileid, $service) {
    $folderId = $fileid;
    $results = $service->files->listFiles(array(
        'q' => "'$folderId' in parents"
    ));
    $klasorler_dizi = [];
    foreach ($results->getFiles() as $file) {
        $klasorler_dizi[$file->getId()] = $file->getName();
    }
    return $klasorler_dizi;
}

Directory creation and file upload function in Google Drive

    function createDirectoryPath($service, $source_selected, $parentId = 'root') {
        // If there is BACKUPDIR in the file path, remove it. So that "../", "./", "BACKUPDIR" does not create the directory on the remote server
        $source = str_replace(array('../', './', BACKUPDIR.'/'), '', $source_selected);
        $directories = explode('/', $source);

            foreach ($directories as $directory) {

                if($directory == end($directories) && !is_dir($source_selected))
                {
                    $dizinveyadosyavarmi = dir_exists($parentId, $service);
                    if(!in_array($directory, $dizinveyadosyavarmi))
                    {
                    insertFile($service, $parentId, $source_selected);
                    }
                }
                else
                {
                    $dizinveyadosyavarmi = dir_exists($parentId, $service);
                    if(in_array($directory, $dizinveyadosyavarmi))
                    {
                        $dizinveyadosyavarmi = array_flip($dizinveyadosyavarmi);
                        $parentId = $dizinveyadosyavarmi[$directory];
                    }
                    else
                    {
                        $parentId = createSubdirectory($service, $parentId, $directory);
                    }
                }
            }
            return $parentId; // ID of the last folder created
    }

Only folder creation function in Google Drive

    function createSubdirectory($service, $parentId, $subdirectoryName) {
        $fileMetadata = new Google_Service_Drive_DriveFile(array(
            'name' => $subdirectoryName,
            'mimeType' => 'application/vnd.google-apps.folder',
            'parents' => $parentId ? array($parentId) : null
        ));

        try {
            $folder = $service->files->create($fileMetadata, array('fields' => 'id'));
            //printf("Klasör ID: %s\n", $folder->id);
            return $folder->id;
        } catch (Exception $e) {
            //echo "Bir hata oluştu: " . $e->getMessage();
        }
        return null;
    }

Code to send to above functions to upload selected files or directories to google drive

$path = ltrim(rtrim($_POST['local_selected_folder_or_file'],'/'),'/');
$rootId = $_POST['selected_directory_in_google_drive'];
if(is_dir($path)){
    $objects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path), RecursiveIteratorIterator::SELF_FIRST);
    foreach($objects as $file => $object){
        if (substr($file, -1) != '.' && substr($file, -2) != '..')
        {
            $file = str_replace(array('\\','\\\\','//'), '/', $file);
            createDirectoryPath($service, $file, $rootId);
        }
        
    }
    echo "<strong>".str_replace(BACKUPDIR.'/', '', $path) . "</strong> Directory Successfully Uploaded to Google Drive";
}else{
    if(createDirectoryPath($service, $path, $rootId))
    {
        echo "<strong>".basename($path) . "</strong> File Successfully Uploaded to Google Drive";
    }
}

My question is:
How to download selected directory from Google Drive including sub-directories and files?

Hello again,

I found a code like below and it creates an array including sub-directories and files as follows

The array below is the array of the google_root directory tree seen in the picture.
Ekran görüntüsü 2023-11-23 213035

How to download google_root folder to local area using below array

Google Drive Array: Array
(
    [1-WLmhRszxo79Dm9AULK0ApmeNnxQKWzj] => Array
        (
            [file_name] => zaman
            [file_type] => application/vnd.google-apps.folder
            [file_id] => 1-WLmhRszxo79Dm9AULK0ApmeNnxQKWzj
            [file_parents] => 1cOcKoHtGqfSiy1KNQZRRcFY8cAyzc7E_
        )

    [1_UHVtoClMdCF4GcH3a-On7eLgNmdUidz] => Array
        (
            [file_name] => cccccccc.zip
            [file_type] => application/zip
            [file_id] => 1_UHVtoClMdCF4GcH3a-On7eLgNmdUidz
            [file_parents] => 1-WLmhRszxo79Dm9AULK0ApmeNnxQKWzj
        )

    [1D1Zy7_YzeaDaWiFZYaQeBuuzVFUtyKYi] => Array
        (
            [file_name] => bir_alt_zaman
            [file_type] => application/vnd.google-apps.folder
            [file_id] => 1D1Zy7_YzeaDaWiFZYaQeBuuzVFUtyKYi
            [file_parents] => 1-WLmhRszxo79Dm9AULK0ApmeNnxQKWzj
        )

    [1cu7vZHdzEbPEWXYDR4qjrJDEuOZSOkSx] => Array
        (
            [file_name] => iki_alt_zaman
            [file_type] => application/vnd.google-apps.folder
            [file_id] => 1cu7vZHdzEbPEWXYDR4qjrJDEuOZSOkSx
            [file_parents] => 1D1Zy7_YzeaDaWiFZYaQeBuuzVFUtyKYi
        )

    [12ubso0UHBKZaijikIAWQ1AKHmWk9mmha] => Array
        (
            [file_name] => webler.zip
            [file_type] => application/zip
            [file_id] => 12ubso0UHBKZaijikIAWQ1AKHmWk9mmha
            [file_parents] => 1cu7vZHdzEbPEWXYDR4qjrJDEuOZSOkSx
        )

    [1TrMSl2SQaopHVs9bcopf5qBZfv9HxJGu] => Array
        (
            [file_name] => web5
            [file_type] => application/vnd.google-apps.folder
            [file_id] => 1TrMSl2SQaopHVs9bcopf5qBZfv9HxJGu
            [file_parents] => 1cu7vZHdzEbPEWXYDR4qjrJDEuOZSOkSx
        )

    [1vcW5gHfhwGPaYQOX3lVyw-RsZBor6Qb1] => Array
        (
            [file_name] => web5.zip
            [file_type] => application/zip
            [file_id] => 1vcW5gHfhwGPaYQOX3lVyw-RsZBor6Qb1
            [file_parents] => 1TrMSl2SQaopHVs9bcopf5qBZfv9HxJGu
        )

    [1XsLv22gRM1VkGrXZO5qAK3xtAQa9pGvq] => Array
        (
            [file_name] => web4
            [file_type] => application/vnd.google-apps.folder
            [file_id] => 1XsLv22gRM1VkGrXZO5qAK3xtAQa9pGvq
            [file_parents] => 1cu7vZHdzEbPEWXYDR4qjrJDEuOZSOkSx
        )

    [17tLeFtNJaMEt7kLpjOgbJrK1KdVJilzg] => Array
        (
            [file_name] => web4.zip
            [file_type] => application/zip
            [file_id] => 17tLeFtNJaMEt7kLpjOgbJrK1KdVJilzg
            [file_parents] => 1XsLv22gRM1VkGrXZO5qAK3xtAQa9pGvq
        )

    [1eTz_xaxEsCxYGRhpX0XlqSN7YmGsui0e] => Array
        (
            [file_name] => web3
            [file_type] => application/vnd.google-apps.folder
            [file_id] => 1eTz_xaxEsCxYGRhpX0XlqSN7YmGsui0e
            [file_parents] => 1cu7vZHdzEbPEWXYDR4qjrJDEuOZSOkSx
        )

    [1QGsOy3AWlf-IkOz7vxj-eTwM-1RgMB-5] => Array
        (
            [file_name] => web3.zip
            [file_type] => application/zip
            [file_id] => 1QGsOy3AWlf-IkOz7vxj-eTwM-1RgMB-5
            [file_parents] => 1eTz_xaxEsCxYGRhpX0XlqSN7YmGsui0e
        )

    [1AsKsnP9GUBDGggopLvxxEPUTPNvyJ9Wf] => Array
        (
            [file_name] => web2
            [file_type] => application/vnd.google-apps.folder
            [file_id] => 1AsKsnP9GUBDGggopLvxxEPUTPNvyJ9Wf
            [file_parents] => 1cu7vZHdzEbPEWXYDR4qjrJDEuOZSOkSx
        )

    [1FcwTku2kmzroOassqAXxR2mgn0BlMmHg] => Array
        (
            [file_name] => web2.zip
            [file_type] => application/zip
            [file_id] => 1FcwTku2kmzroOassqAXxR2mgn0BlMmHg
            [file_parents] => 1AsKsnP9GUBDGggopLvxxEPUTPNvyJ9Wf
        )

    [1JgCPF8ZCycmLRmQ_5EuKqPwpFxpLZEEN] => Array
        (
            [file_name] => web1
            [file_type] => application/vnd.google-apps.folder
            [file_id] => 1JgCPF8ZCycmLRmQ_5EuKqPwpFxpLZEEN
            [file_parents] => 1cu7vZHdzEbPEWXYDR4qjrJDEuOZSOkSx
        )

    [1SRbkZhZodrHRyZb_5MryxqpS6MPrfIJJ] => Array
        (
            [file_name] => web1.zip
            [file_type] => application/zip
            [file_id] => 1SRbkZhZodrHRyZb_5MryxqpS6MPrfIJJ
            [file_parents] => 1JgCPF8ZCycmLRmQ_5EuKqPwpFxpLZEEN
        )

    [1E7Djf6Cbz26FFABnfarSGTqT7aoQ5FTm] => Array
        (
            [file_name] => ddddddd.zip
            [file_type] => application/zip
            [file_id] => 1E7Djf6Cbz26FFABnfarSGTqT7aoQ5FTm
            [file_parents] => 1D1Zy7_YzeaDaWiFZYaQeBuuzVFUtyKYi
        )

    [1I76_PndAIcz83CcUnhBp7-lYKxFW6LqX] => Array
        (
            [file_name] => bbbbbbb.zip
            [file_type] => application/zip
            [file_id] => 1I76_PndAIcz83CcUnhBp7-lYKxFW6LqX
            [file_parents] => 1cOcKoHtGqfSiy1KNQZRRcFY8cAyzc7E_
        )

    [1JhskJ38cgHUuMhAkBCgb6sYLCIhPKpsU] => Array
        (
            [file_name] => bbbbbbb
            [file_type] => application/vnd.google-apps.folder
            [file_id] => 1JhskJ38cgHUuMhAkBCgb6sYLCIhPKpsU
            [file_parents] => 1cOcKoHtGqfSiy1KNQZRRcFY8cAyzc7E_
        )

    [10ttCOX_kMiYjf7CiKQ-wTekO15nliWgi] => Array
        (
            [file_name] => aaaaaaaa.zip
            [file_type] => application/zip
            [file_id] => 10ttCOX_kMiYjf7CiKQ-wTekO15nliWgi
            [file_parents] => 1cOcKoHtGqfSiy1KNQZRRcFY8cAyzc7E_
        )

    [1miix7MZpPLaSWdyUQ5MJA57-iqQvF-Fg] => Array
        (
            [file_name] => aaaaaaaa
            [file_type] => application/vnd.google-apps.folder
            [file_id] => 1miix7MZpPLaSWdyUQ5MJA57-iqQvF-Fg
            [file_parents] => 1cOcKoHtGqfSiy1KNQZRRcFY8cAyzc7E_
        )

)

The PHP code is below

// Getting the Drive Files
$copy_from_id = '1cOcKoHtGqfSiy1KNQZRRcFY8cAyzc7E_'; //google_root ID
$optParams = array(
    'fields' => 'nextPageToken, files(*)',
    'q' => "'$copy_from_id' in parents"
);
$files_arr = array();
$results = $service->files->listFiles($optParams);
if (count($results->getFiles()) !== 0) {
    $files = $results->getFiles();
    $files_arr = recursivelyGetGDriveFolderContents($files_arr, $service, $files);
    //return $files_arr;
    
}

// My recursive function
function recursivelyGetGDriveFolderContents($files_arr, $service, $files){
  // Instead of setting my main array in this function I pass data into it via the function argument
  foreach ($files as $file) {
    $file_id = $file->getId();
    $file_name = $file->getName();
    $file_type = $file->getMimeType();
    $file_parents = $file->getParents();
    $return_file = array(
      'file_name' => $file_name,
      'file_type' => $file_type,
      'file_id' => $file_id,
      'file_parents' => $file_parents[0],
      
    );
    $files_arr[$file_id] = $return_file;
    if($file_type == 'application/vnd.google-apps.folder'){
      $optParams = array(
        'fields' => 'nextPageToken, files(*)',
        'q' => "'$file_id' in parents"
      );
      $results = $service->files->listFiles($optParams);
      if (count($results->getFiles()) !== 0) {
        $files_sub = $results->getFiles();
        $files_sub_arr = recursivelyGetGDriveFolderContents($files_arr, $service, $files_sub);
        // I added this inner loop to add each child to the main parent array so that I didn't have nested arrays
        foreach($files_sub_arr as $file_sub){
          $file_sub_id = $file_sub['file_id'];
          $files_arr[$file_sub_id] = $file_sub;
        }
      } 
    }
  }
  return $files_arr;
}

I think it will be possible to download the files with the code given in the url below.
However, there is a problem, this code lists all files, I wonder what should be done to list the directory I specified?
https://faridmovsumov.medium.com/how-to-list-sub-and-shared-folders-by-using-google-drive-api-with-a-php-client-dc45db2c1f75

I disabled this line to get the following list

//$parameters['q'] = "mimeType='application/vnd.google-apps.folder' and trashed=false";

When I specify the directory ID I want to specify as follows, it lists only the files in the main directory.

$parameters['q'] = "'1cOcKoHtGqfSiy1KNQZRRcFY8cAyzc7E_' in parents";
Sponsor our Newsletter | Privacy Policy | Terms of Service