views:

59

answers:

3

I have seen functions to list all file in a directory but how can I list all the files in sub-directories too, so it returns an array like?

$files = files("foldername");

So $files is something similar to

array("file.jpg", "blah.word", "name.fileext")
+3  A: 

I think you're looking for php's glob function. You can call glob(**) to get a recursive file listing.

EDIT: I realized that my glob doesn't work reliably on all systems so I submit this much prettier version of the accepted answer.

function rglob($pattern='*', $flags = 0, $path='')
{
    $paths=glob($path.'*', GLOB_MARK|GLOB_ONLYDIR|GLOB_NOSORT);
    $files=glob($path.$pattern, $flags);
    foreach ($paths as $path) { $files=array_merge($files,rglob($pattern, $flags, $path)); }
    return $files;
}

from: http://www.phpfreaks.com/forums/index.php?topic=286156.0

Chuck Vose
+3  A: 
<?php
foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator('.')) as $filename)
{
        echo "$filename\n";
}
?>
konforce
+1  A: 

So you're looking for a recursive directory listing?

function directoryToArray($directory, $recursive) {
    $array_items = array();
    if ($handle = opendir($directory)) {
        while (false !== ($file = readdir($handle))) {
            if ($file != "." && $file != "..") {
                if (is_dir($directory. "/" . $file)) {
                    if($recursive) {
                        $array_items = array_merge($array_items, directoryToArray($directory. "/" . $file, $recursive));
                    }
                    $file = $directory . "/" . $file;
                    $array_items[] = preg_replace("/\/\//si", "/", $file);
                } else {
                    $file = $directory . "/" . $file;
                    $array_items[] = preg_replace("/\/\//si", "/", $file);
                }
            }
        }
        closedir($handle);
    }
    return $array_items;
}

http://snippets.dzone.com/posts/show/155

Ruel