• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 349
  • Last Modified:

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
0
Slim81
Asked:
Slim81
1 Solution
 
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

Featured Post

Upgrade your Question Security!

Your question, your audience. Choose who sees your identity—and your question—with question security.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now