PHP list all files in directory

77,576

Solution 1

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

    echo "$filename\n";
}


PHP documentation:

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']));
Share:
77,576

Related videos on Youtube

Mark Lalor
Author by

Mark Lalor

I began my programming journey at the age of 11. My 5th grade teacher showed me that I could save a file on notepad with another file extension than .txt! Thus began my interest in HTML, CSS, Javascript, PHP, PHP GD, jQuery, SQL, C#, .NET Framework, C, C++, mobile apps, DragonFireSDK (7/10 would not use again), Objective C, and Java, in that order. I learned only through books and the internet, which is why I asked many dumb questions years ago. I like to look back on them and reminisce on my bad programming skills and problem-solving.

Updated on September 02, 2020

Comments

  • Mark Lalor
    Mark Lalor over 3 years

    Possible Duplicate:
    Get the hierarchy of a directory with PHP
    Getting the names of all files in a directory with PHP

    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")
    
  • superultranova
    superultranova about 13 years
    +1 for SPL. IMO its time (has been for a while) to start using SPL instead of these huge, slow procedural blocks.
  • T.Todua
    T.Todua about 11 years
    Full code (change foldername) - <?php $path = realpath('yourfolder/examplefolder'); foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path)) as $filename) { echo "$filename\n"; } ?>
  • Kloar
    Kloar almost 11 years
    Oh wow... Compare this to the behemoth above. Amazing.
  • machineaddict
    machineaddict over 10 years
    Do not use regexes in recursion, they tend to be very slow! In your case use rtrim function.
  • Bruce Kirkpatrick
    Bruce Kirkpatrick over 10 years
    I rewrote this as a gist to be more efficient and only return files: gist.github.com/brucekirkpatrick/8528710
  • Gras Double
    Gras Double almost 9 years
    It includes . and .. special dirs. Hopefully you can filter them out by adding a !$filename->isDir() test (there is no isDot(), see SplFileInfo).
  • Gras Double
    Gras Double almost 9 years
    Also, useful links to PHP doc: RecursiveDirectoryIterator - RecursiveIteratorIterator