42

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!

lewisqic
  • 1,943
  • 5
  • 21
  • 19

6 Answers6

100

Try glob

Something like:

 foreach(glob('./images/*.*') as $filename){
     echo $filename;
 }
Anthony
  • 36,459
  • 25
  • 97
  • 163
a.yastreb
  • 1,493
  • 1
  • 10
  • 11
20

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] => .
)
Sampson
  • 265,109
  • 74
  • 539
  • 565
  • 1
    Do you know why scandir has two array keys that contain periods? Seems kinda strange to me. – lewisqic Jan 13 '10 at 20:29
  • 4
    In brief, the periods are the standard directory annotators in Linux. The single period denotes the current directory and the double period denotes the parent directory. – Mario Awad Dec 29 '12 at 18:02
14

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

Gordon
  • 312,688
  • 75
  • 539
  • 559
  • with GLOB if you have this error "PHP glob(): At least one of the passed flags is invalid or not supported on this platform in" . Here is the solution : http://stackoverflow.com/questions/26763115/php-glob-at-least-one-of-the-passed-flags-is-invalid-or-not-supported-on-this . **just in case** – diego matos - keke Nov 13 '15 at 01:35
  • @keke 1 corresponds to `GLOB_ERR`, which was added in PHP 5.1.0. If that causes an error, you are using an outdated PHP version. Consider updating it. Then again, it's always better to use the constant itself instead of it's value, so I should have used `GLOB_ERR` instead in the first place. I removed it from the answer now because it's not needed for the usecase at hand. – Gordon Nov 13 '15 at 08:25
3

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";
 }
Anthony
  • 36,459
  • 25
  • 97
  • 163
2

This will gives you all the files in links.

<?php
$path = $_SERVER['DOCUMENT_ROOT']."/your_folder/"; 

$files = scandir($path);
$count=1;
foreach ($files as $filename)
{
    if($filename=="." || $filename==".." || $filename=="download.php" || $filename=="index.php")
    {
        //this will not display specified files
    }
    else
    {
        echo "<label >".$count.".&nbsp;</label>";
        echo "<a href="download.php/?filename=".$filename."">".$filename."</a>
";
        $count++;
    }
}
?>
Taryn
  • 242,637
  • 56
  • 362
  • 405
Hardik
  • 1,283
  • 14
  • 34
-1

Maybe this function can be useful in the future. You can manipulate the function if you need to echo things or want to do other stuff.

$wavs = array();
$wavs = getAllFiles('folder_name',$wavs,'wav');

$allTypesOfFiles = array();
$wavs = getAllFiles('folder_name',$allTypesOfFiles);

//explanation of arguments from the getAllFiles() function
//$dir -> folder/directory you want to get all the files from.
//$allFiles -> to store all the files in and return in the and.
//$extension -> use this argument if you want to find specific files only, else keept empty to find all type of files.

function getAllFiles($dir,$allFiles,$extension = null){
    $files = scandir($dir);
    foreach($files as $file){           
        if(is_dir($dir.'/'.$file)) {
            $allFiles = getAllFiles($dir.'/'.$file,$allFiles,$extension);
        }else{
            if(empty($extension) || $extension == pathinfo($dir.'/'.$file)['extension']){
                array_push($allFiles,$dir.'/'.$file);
            }
        }
    }
    return $allFiles;
}
freeji
  • 3
  • 4