Create array with file names from directory

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
DroopyPawn
Forum Newbie
Posts: 4
Joined: Sun Nov 07, 2004 6:06 pm

Create array with file names from directory

Post by DroopyPawn »

I'm sure this is a simple task but how do I create an array containing a list of file names in my directory (and optionally - subdirectories) ? I only want .html files in the list.

And then, how would I display a list of links to those pages (as html) using each file's META TITLE tag?
User avatar
BDKR
DevNet Resident
Posts: 1207
Joined: Sat Jun 08, 2002 1:24 pm
Location: Florida
Contact:

Post by BDKR »

Have you checked http://us2.php.net/manual/en/class.dir.php ? There is a good example of how to use the dir class. Once you've created an array with the dir class, iterate over it and check file names.

Cheers
rehfeld
Forum Regular
Posts: 741
Joined: Mon Oct 18, 2004 8:14 pm

Post by rehfeld »

see if this works, i havent tested it,



Code: Select all

<?php


function recursive_scandir($dir)
{
    $filenames = array();

    if (!is_dir($dir) || !is_readable($dir)) {
        return false;
    }

    if ($handle = opendir($dir)) {
        while (false !== ($filename = readdir($handle))) {

            if ($filename === '.' || $filename === '..') continue;

            if (is_dir("$dir/$filename")) {

                $nested_filenames = recursive_scandir("$dir/$filename");
                if (is_array($nested_filenames)) {
                    $filenames = array_merge($filenames, $nested_filenames);
                }

            } else {
                $filenames[] = "$dir/$filename";
            }
        }
        closedir($handle);
    }

    return $filenames;
}


$dir = 'your_dir';
$all_files = recursive_scandir($dir);
print_r($all_files); // just so you can see it all

$html_files = array();

foreach ($all_files as $file) {
    if ('html' === end(explode('.', $file))) {
        $html_files[] = $file;
    }
}

print_r($html_files);



?>
Post Reply