PHP Get file names from folder and store in array

Hey guys and gals,
This is my first step into PHP!  I have built quite a few basic programs using ASP, but this is my first with PHP.  

I am trying to get a list of file names from a folder and then store them in an array.  Any ideas on how I can do this?

Please remember I am new!

Thanks,
Slim
LVL 4
Slim81Asked:
Who is Participating?
 
Greg AlexanderLead DeveloperCommented:
Try this:
<?php
if ($handle = opendir('.')) {
    while (false !== ($file = readdir($handle))) {
        if ($file != "." && $file != "..") {
            $file_array[] = $file;
        }
    }
    closedir($handle);
}

//print the files
print_r($file_array);
?>

Open in new window

0
 
Marco GasiFreelancerCommented:
Or try

 
$dir = 'your_dir_path';
$filelist = scandir($dir) or die('Invalid directory name');
foreach ($filelist as $file){
  if (is_file('$dir/$file') && $file != '.' && $file != '..'){
    $file_array[] = $file;
  }
}

Open in new window


You can also use an iterator:
$dir = 'your_dir_path';

$iterator = new DirectoryIterator($dir);

//back to the begin of directory
$iterator->rewqind;

while ($iterator->valid()){
  if ($iterator->isFile() && !$iterator->isDot()){
    $file_array[] = $iterator->getFilename();
  }
  $iterator->next();
}

Open in new window


Cheers
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.