Knowledge Base

An archive of my personal knowledge base.

PHP - List Files and Directories

Cristian Sulea

The older way is scandir but DirectoryIterator is probably the best way. There's also readdir (to be used with opendir) and glob.

The DirectoryIterator class

foreach (new DirectoryIterator('.') as $file) {
    if ($file->isDot()) continue;
    print $file->getFilename() . '<br>';
}

scandir

$files = scandir('.');
foreach($files as $file) {
    if ($file == '.' || $file == '..') continue;
    print $file . '<br>';
}

opendir and readdir

if ($handle = opendir('.')) {
    while (false !== ($file = readdir($handle))) {
        if($file == '.' || $file == '..') continue;
        print $file . '<br>';
    }
    closedir($handle);
}

glob

foreach (glob("*") as $file) {
    if ($file == '.' || $file == '..') continue;
    print $file . '<br>';
}

Resources

Share on Twitter