tags:

views:

157

answers:

4

Hi,

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!

+1  A: 

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] => .
)
Jonathan Sampson
Do you know why scandir has two array keys that contain periods? Seems kinda strange to me.
lewisqic
+1  A: 

Either scandir() as suggested elsewhere or

  • glob() — Find pathnames matching a pattern

Example:

$images = scandir("./images/*.gif", 1);
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 DirectoryIterator:

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

To go into subdirectories as well, use RecursiveDirectoryIterator:

$items = new RecursiveIteratorIterator(new RecursiveDirectoryIterator('.'),
                                       RecursiveIteratorIterator::SELF_FIRST);
foreach($items as $item) {
    echo $file, PHP_EOL;
}

To ignore filenames, remove RecursiveIteratorIterator::SELF_FIRST

Gordon
+1  A: 

Try glob

Something like:

 foreach(glob('./images/*.*') as $filename){
     echo $filename;
 }
habicht
+1  A: 

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

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