0

I have a directory called 25
and I want to print the list of files in that directory using PHP.
How can I ?

Edited by Priti_P

5
Contributors
6
Replies
58
Views
4 Years
Discussion Span
Last Post by Priti_P
-1
    $files = array(  );
    $dir = opendir( $name );
    while( false !== ($file = readdir($dir)) )
    {
      if( $file != '.' && $file != '..' )
      {
        $pop = explode('.',$file);
        $ext = "";
        if(count($pop)>1) $ext = array_pop($pop);
        $files[implode('.',$pop)][] = $ext;
      }
    }
    closedir($dir);
    print_r($files);
1

I love glob. But you could also use DirectoryIterator:

function getFiles($dir='.')
{
    $out = '';
    foreach (new DirectoryIterator($dir) as $file) {
        if($file->isDot() || $file->isDir()) continue;
        $out .= $file->getFilename() . "<br />\n";
    }
    return $out;
}

echo getFiles();
echo getFiles('./includes');

Alternatively, you could store to an array:

function getFiles($dir='.')
{
    $out = array();
    foreach (new DirectoryIterator($dir) as $file) {
        if($file->isDot() || $file->isDir()) continue;
        $out[] = $file->getFilename();
    }
    return $out;
}

print_r( getFiles() );
print_r( getFiles('./includes') );

Edited by diafol

Votes + Comments
Iterators; one of the most underused feature in PHP.
0

There is also a function called scandir, here's an example.

$dir = scandir("directory");
/* Loop through each file */
foreach ($dir as $file) {
    /* Ignore these */
    if ($file != '.' && $file != '..') {
        echo $file;
    }
}
0

I've heard that the "best" way is to use globIterator() - but only available since 5.3.0.

There seems to be a bug in my version, so I can't test for speed comparison.

0

@NardCake:
awesome dude...!!!
thanks!!
I had totaly forgotten about this function . My bad.
Thanks for remining me!!
@all: thanks!!

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.