Getting the names of all files in a directory with PHP

149,126

Solution 1

Don't bother with open/readdir and use glob instead:

foreach(glob($log_directory.'/*.*') as $file) {
    ...
}

Solution 2

SPL style:

foreach (new DirectoryIterator(__DIR__) as $file) {
  if ($file->isFile()) {
      print $file->getFilename() . "\n";
  }
}

Check DirectoryIterator and SplFileInfo classes for the list of available methods that you can use.

Solution 3

As the accepted answer has two important shortfalls, I'm posting the improved answer for those new comers who are looking for a correct answer:

foreach (array_filter(glob('/Path/To/*'), 'is_file') as $file)
{
    // Do something with $file
}
  1. Filtering the globe function results with is_file is necessary, because it might return some directories as well.
  2. Not all files have a . in their names, so */* pattern sucks in general.

Solution 4

You need to surround $file = readdir($handle) with parentheses.

Here you go:

$log_directory = 'your_dir_name_here';

$results_array = array();

if (is_dir($log_directory))
{
        if ($handle = opendir($log_directory))
        {
                //Notice the parentheses I added:
                while(($file = readdir($handle)) !== FALSE)
                {
                        $results_array[] = $file;
                }
                closedir($handle);
        }
}

//Output findings
foreach($results_array as $value)
{
    echo $value . '<br />';
}

Solution 5

Just use glob('*'). Here's Documentation

Share:
149,126
DexterW
Author by

DexterW

Developer in Austin, Texas.

Updated on August 10, 2021

Comments

  • DexterW
    DexterW almost 3 years

    For some reason, I keep getting a '1' for the file names with this code:

    if (is_dir($log_directory))
    {
        if ($handle = opendir($log_directory))
        {
            while($file = readdir($handle) !== FALSE)
            {
                $results_array[] = $file;
            }
            closedir($handle);
        }
    }
    

    When I echo each element in $results_array, I get a bunch of '1's, not the name of the file. How do I get the name of the files?