61

How to get the file names inside a directory using PHP?

I couldn't find the relevant command using Google, so I hope that this question will help those who are asking along the similar lines.

Graviton
  • 81,782
  • 146
  • 424
  • 602

4 Answers4

93

There's a lot of ways. The older way is scandir but DirectoryIterator is probably the best way.

There's also readdir (to be used with opendir) and glob.

Here are some examples on how to use each one to print all the files in the current directory:

DirectoryIterator usage: (recommended)

foreach (new DirectoryIterator('.') as $file) {
    if($file->isDot()) continue;
    print $file->getFilename() . '<br>';
}

scandir usage:

$files = scandir('.');
foreach($files as $file) {
    if($file == '.' || $file == '..') continue;
    print $file . '<br>';
}

opendir and readdir usage:

if ($handle = opendir('.')) {
    while (false !== ($file = readdir($handle))) {
        if($file == '.' || $file == '..') continue;
        print $file . '<br>';
    }
    closedir($handle);
}

glob usage:

foreach (glob("*") as $file) {
    if($file == '.' || $file == '..') continue;
    print $file . '<br>';
}

As mentioned in the comments, glob is nice because the asterisk I used there can actually be used to do matches on the files, so glob('*.txt') would get you all the text files in the folder and glob('image_*') would get you all files that start with image_

Paolo Bergantino
  • 480,997
  • 81
  • 517
  • 436
  • 8
    One advantage of glob is you can filter files easily, for example `glob('*.txt')` will list all text files. – DisgruntledGoat Jul 06 '09 at 14:20
  • 1
    @EvilChookie: The only thing I can think of is that glob and scandir load the entire file structure into memory automatically, which is just something you should be aware of. Not sure about anything else. – Paolo Bergantino Jul 07 '09 at 18:17
  • @EvilChookie: see here some were benchmarked: http://stackoverflow.com/questions/2120287/directory-to-array-with-php/2120496#2120496 – Marco Demaio Feb 05 '12 at 17:20
  • 3
    @Marco: the link you provided is not working anymore. I found a [benchmark at phparch.com](http://www.phparch.com/2010/04/putting-glob-to-the-test/) in case someone is interested. – Lando Nov 27 '12 at 14:56
  • 1
    @Lando: interesting link. I hate when moderator here on SO deletes old questions that are very useful and it's not even possible to sse them anymore. – Marco Demaio Nov 28 '12 at 15:20
  • +1 for most complete answer for this and related (duplicate) questions – The Thirsty Ape Aug 09 '13 at 16:50
16

The Paolo Bergantino's answer was fine but is now outdated!
Please consider the below official ways to get the Files inside a directory.


FilesystemIterator

FilesystemIterator has many new features compared to its ancestor DirectoryIterator as for instance the possibility to avoid the statement if($file->isDot()) continue;. See also the question Difference between DirectoryIterator and FilesystemIterator.

$it = new FilesystemIterator(__DIR__);
foreach ($it as $fileinfo) {
    echo $fileinfo->getFilename() , PHP_EOL;
}

RecursiveDirectoryIterator

This snippet lists PHP files in all sub-directories.

$dir   = new RecursiveDirectoryIterator(__DIR__);
$flat  = new RecursiveIteratorIterator($dir);
$files = new RegexIterator($flat, '/\.php$/i');
foreach($files as $file) {
    echo $file , PHP_EOL;
}

See also the Wrikken's answer.

Community
  • 1
  • 1
oHo
  • 51,447
  • 27
  • 165
  • 200
2

Most of the time I imagine you want to skip . and ... Here is that with recursion:

<?php
$o_dir = new RecursiveDirectoryIterator('.', FilesystemIterator::SKIP_DOTS);
$o_iter = new RecursiveIteratorIterator($o_dir);
foreach ($o_iter as $o_name) {
   echo $o_name->getFilename();
}

https://php.net/class.recursivedirectoryiterator

Zombo
  • 1
  • 62
  • 391
  • 407
0

The old way would be:

<?php
    $path = realpath('.'); // put in your path here
    $dir_handle = @opendir($path) or die("Unable to open $path");
    $directories = array();
    while ($file = readdir($dir_handle)) 
        $directories[] = $file;
    closedir($dir_handle);
?>

As already mentioned the directory iterator might be the better way for PHP 5.

Daff
  • 43,734
  • 9
  • 106
  • 120