How to read a list of files from a folder using PHP?


Question

I want to read a list the names of files in a folder in a web page using php. is there any simple script to acheive it?

1
39
4/6/2009 9:18:50 AM

Accepted Answer

The simplest and most fun way (imo) is glob

foreach (glob("*.*") as $filename) {
    echo $filename."<br />";
}

But the standard way is to use the directory functions.

if (is_dir($dir)) {
    if ($dh = opendir($dir)) {
        while (($file = readdir($dh)) !== false) {
            echo "filename: .".$file."<br />";
        }
        closedir($dh);
    }
}

There are also the SPL DirectoryIterator methods. If you are interested

104
6/3/2012 7:01:39 AM

There is this function scandir():

$dir = 'dir';
$files = scandir($dir, 0);
for($i = 2; $i < count($files); $i++)
    print $files[$i]."<br>";

More here in the php.net manual


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon