PHP: Get list of all filenames contained within my images directory

Viewed 85643

I have been trying to figure out a way to list all files contained within a directory. I'm not quite good enough with php to solve it on my own so hopefully someone here can help me out.

I need a simple php script that will load all filenames contained within my images directory into an array. Any help would be greatly appreciated, thanks!

6 Answers

Try glob

Something like:

 foreach(glob('./images/*.*') as $filename){
     echo $filename;
 }

scandir() - List files and directories inside the specified path

$images = scandir("images", 1);
print_r($images);

Produces:

Array
(
    [0] => apples.jpg
    [1] => oranges.png
    [2] => grapes.gif
    [3] => ..
    [4] => .
)

Either scandir() as suggested elsewhere or

  • glob() — Find pathnames matching a pattern

Example

$images = glob("./images/*.gif");
print_r($images);

/* outputs 
Array (
   [0] => 'an-image.gif' 
   [1] => 'another-image.gif'
)
*/

Or, to walk over the files in directory directly instead of getting an array, use

Example

foreach (new DirectoryIterator('.') as $item) {
    echo $item, PHP_EOL;
} 

To go into subdirectories as well, use RecursiveDirectoryIterator:

$items = new RecursiveIteratorIterator(
    new RecursiveDirectoryIterator('.'),
    RecursiveIteratorIterator::SELF_FIRST
);

foreach($items as $item) {
    echo $item, PHP_EOL;
}

To list just the filenames (w\out directories), remove RecursiveIteratorIterator::SELF_FIRST

You can also use the Standard PHP Library's DirectoryIterator class, specifically the getFilename method:

 $dir = new DirectoryIterator("/path/to/images");
 foreach ($dir as $fileinfo) {
      echo $fileinfo->getFilename() . "\n";
 }
Related