array of existing files

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
bimo
Forum Contributor
Posts: 100
Joined: Fri Apr 16, 2004 11:18 pm
Location: MD

array of existing files

Post by bimo »

Hi all,

Is there an array or function or some way that I can access all of the filenames that exist in a given location? I am trying to write a search function that can return multiple files (or their names at least).

I thought there might be something similar to the $_POST array except for files that exist in a given directory.

Thanks for your help,

Holly
kettle_drum
DevNet Resident
Posts: 1150
Joined: Sun Jul 20, 2003 9:25 pm
Location: West Yorkshire, England

Post by kettle_drum »

Kind of. Take a look at this example from the manual:

Code: Select all

<?php
$dir = "/tmp/";

// Open a known directory, and proceed to read its contents
if (is_dir($dir)) {
   if ($dh = opendir($dir)) {
       while (($file = readdir($dh)) !== false) {
           echo "filename: $file : filetype: " . filetype($dir . $file) . "\n";
       }
       closedir($dh);
   }
}
?>
timvw
DevNet Master
Posts: 4897
Joined: Mon Jan 19, 2004 11:11 pm
Location: Leuven, Belgium

Post by timvw »

Code: Select all

function filesInDirectory($directory) {
  $results = array();
  if ($handler = @opendir($directory)) {
    while ($file = readdir($handler)) {
      if (!is_dir($directory.'/'.$file)) {
        $results[] = $file;
      }
    }
    closedir($handler);
  }
  return $results;
}
with a little imagination and recursion it does everything you want ;)
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

there's [php_man]glob[/php_man] too.. if you have a newer version of php.
User avatar
bimo
Forum Contributor
Posts: 100
Joined: Fri Apr 16, 2004 11:18 pm
Location: MD

Post by bimo »

you guys are fantastic! All of your sugestions look great but unfortuanately I have to run to class and don't have time to check them out right now.

I'll post back if I run into any snags (which I'm sure I will.

h
User avatar
bimo
Forum Contributor
Posts: 100
Joined: Fri Apr 16, 2004 11:18 pm
Location: MD

Post by bimo »

While at the glob() page I saw that someone created a function that is just what I am looking for: preg_find(), which matches files against a given pattern and puts them in an array.

http://www.pgregg.com/projects/php/code/preg_find.phps


thanks again, all
Post Reply