Jens Törnell
Jens Törnell

Reputation: 24798

Get folders with PHP glob - unlimited levels deep

I have this working function that finds folders and creates an array.

function dua_get_files($path)
{
    foreach (glob($path . "/*", GLOB_ONLYDIR) as $filename)
    {
        $dir_paths[] = $filename;   
    }
    return $dir_paths;
}

This function can only find the directories on the current location. I want to find the directory paths in the child folders and their children and so on.

The array should still be a flat list of directory paths.

An example of how the output array should look like

$dir_path[0] = 'path/folder1';
$dir_path[1] = 'path/folder1/child_folder1';
$dir_path[2] = 'path/folder1/child_folder2';
$dir_path[3] = 'path/folder2';
$dir_path[4] = 'path/folder2/child_folder1';
$dir_path[5] = 'path/folder2/child_folder2';
$dir_path[6] = 'path/folder2/child_folder3';

Upvotes: 14

Views: 30332

Answers (6)

Beracah
Beracah

Reputation: 362

For PHP, if you are on a linux/unix, you can also use backticks (shell execution) with the unix find command. Directory searching on the filesystem can take a long time and hit a loop -- the system find command is already built for speed and to handle filesystem loops. In other words, the system exec call is likely to cost far less cpu-time than using PHP itself to search the filesystem tree.

$dirs = `find $path -type d`;

Remember to sanitize the $path input, so other users don't pass in security compromising path names (like from the url or something).

To put it into an array

$dirs = preg_split("/\s*\n+\s*/",`find $path -type d`,-1,PREG_SPLIT_NO_EMPTY);

Upvotes: 0

crisc2000
crisc2000

Reputation: 1232

You can use php GLOB function, but you must create a recursive function to scan directories at infinite level depth. Then store results in a global variable.

function dua_get_files($path) {
    global $dir_paths; //global variable where to store the result
    foreach ($path as $dir) { //loop the input
        $dir_paths[] = $dir; //can use also "basename($dir)" or "realpath($dir)"
        $subdir =  glob($dir . DIRECTORY_SEPARATOR . '*', GLOB_ONLYDIR); //use DIRECTORY_SEPARATOR to be OS independent
        if (!empty($subdir)) { //if subdir is not empty make function recursive
            dua_get_files($subdir); //execute the function again with current subdir
        }
    }
}

//usage:
$path = array('galleries'); //suport absolute or relative path. support one or multiple path
dua_get_files($path);
print('<pre>'.print_r($dir_paths,true).'</pre>'); //debug

Upvotes: 1

Crusader
Crusader

Reputation: 1200

Very strange - everybody advice recursion, but better just cycle:

$dir ='/dir';
while($dirs = glob($dir . '/*', GLOB_ONLYDIR)) {
  $dir .= '/*';
  if(!$result) {
     $result = $dirs;
   } else {
      $result = array_merge($result, $dirs);
   }
}

Upvotes: 10

Pascal MARTIN
Pascal MARTIN

Reputation: 401182

If you want to recursively work on directories, you should take a look at the RecursiveDirectoryIterator.

$path = realpath('/etc');

$objects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path), RecursiveIteratorIterator::SELF_FIRST);
foreach($objects as $name => $object){
    echo "$name\n";
}

Upvotes: 20

DJafari
DJafari

Reputation: 13545

Use this function :

function dua_get_files($path)
{
    $dir_paths = array();
    foreach (glob($path . "/*", GLOB_ONLYDIR) as $filename)
    {
        $dir_paths[] = $filename;
        $a = glob("$filename/*", GLOB_ONLYDIR);
        if( is_array( $a ) )
        {
            $b = dua_get_files( "$filename/*" );
            foreach( $b as $c )
            {
                $dir_paths[] = $c;
            }
        }
    }
    return $dir_paths;
}

Upvotes: 4

Alix Axel
Alix Axel

Reputation: 154691

Try this instead:

function dua_get_files($path)
{
    $data = array();
    $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path), RecursiveIteratorIterator::SELF_FIRST);

    foreach ($files as $file)
    {
        if (is_dir($file) === true)
        {
            $data[] = strval($file);
        }
    }

    return $data;
}

Upvotes: 6

Related Questions