如何使用PHP从文件夹中读取文件列表?

Aru*_*lai 41 php file

我想使用php读取网页中文件夹中文件名的列表.是否有任何简单的脚本来实现它?

Óla*_*age 107

最简单,最有趣的方式(imo)是glob

foreach (glob("*.*") as $filename) {
    echo $filename."<br />";
}
Run Code Online (Sandbox Code Playgroud)

但标准方法是使用目录功能.

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

还有SPL DirectoryIterator方法.如果你感兴趣

  • `$dir = getcwd();` 获取当前工作目录。 (2认同)

小智 14

有这个函数scandir():

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

更多这里的php.net手册


Bru*_*lza 12

这就是我喜欢做的事情:

$files = array_values(array_filter(scandir($path), function($file) use ($path) { 
    return !is_dir($path . '/' . $file);
}));

foreach($files as $file){
    echo $file;
}
Run Code Online (Sandbox Code Playgroud)