PHP list all files in directory [duplicate]

Solution 1:

foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator('.')) as $filename)
{
    // filter out "." and ".."
    if ($filename->isDir()) continue;

    echo "$filename\n";
}


PHP documentation:

  • RecursiveDirectoryIterator
  • RecursiveIteratorIterator

Solution 2:

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;
}

Solution 3:

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

Solution 4:

function files($path,&$files = array())
{
    $dir = opendir($path."/.");
    while($item = readdir($dir))
        if(is_file($sub = $path."/".$item))
            $files[] = $item;else
            if($item != "." and $item != "..")
                files($sub,$files); 
    return($files);
}
print_r(files($_SERVER['DOCUMENT_ROOT']));