Delete directory from private folder programatically? I'm using D8, and am writing a cron task to remove old backups from my private files directory. The backups are generated in private://db_backups/date-of-backups/backup.gz. The following code is properly deleting the actual backup files, but it is not removing the parent date directory. I am not receiving any errors in the drupal or server logs, so I'm a bit lost as to what's causing the failure.

function custom_changes_cron() {
    drupal_set_message(t('Custom cron function has run.'), 'status');
    $private_path = PrivateStream::basePath();
    $interval = strtotime('-430 hours');
    foreach(glob($private_path . '/backup_db/*' , GLOB_ONLYDIR) as $folder) {
        if (filemtime($folder) &lt;= $interval ) {
            $files = glob("$folder/*"); // get all file names
            foreach($files as $file){ // iterate files
              if(is_file($file))
              unlink($file); // delete file
            }

            // Have tried both of the following
            rm_dir($folder);
            drupal_rmdir($folder);  
        }
    }
}
Note that glob('*') ignores all hidden files by default. This means it does not return files that start with a dot (e.g. .file).  If you want to match those files too, you can use {,.}*  as the pattern with the GLOB_BRACE flag. This will include the special cases . and .. so you need to exclude those by using {,.}[!.,!..]*.

So in summary, try the following:

$files = glob("$folder/" . '{,.}[!.,!..]*',GLOB_MARK|GLOB_BRACE);


As a sidenote: you mention you tried using rm_dir. I assume you mean rmdir?