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

    $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);
Member Avatar for diafol

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') );
commented: Iterators; one of the most underused feature in PHP. +8

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;
    }
}
Member Avatar for diafol

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.

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.