PHP opendir()仅列出文件夹

Jef*_*mas 15 php opendir

我想使用opendir()仅列出特定文件夹中的文件夹(即/ www/site /).我想从列表中排除文件以及'.' 以及出现在linux文件夹列表中的'..'文件夹.我该怎么做呢?

Jas*_*ary 18

查看readdir()PHP文档.它包含了一个这样的例子.

为了完整性:

<?php
if ($handle = opendir('.')) {
    $blacklist = array('.', '..', 'somedir', 'somefile.php');
    while (false !== ($file = readdir($handle))) {
        if (!in_array($file, $blacklist)) {
            echo "$file\n";
        }
    }
    closedir($handle);
}
?>
Run Code Online (Sandbox Code Playgroud)

只需更改opendir('.')到您的目录,即opendir('/www/sites/')更新$blacklist以包含您不希望输出的文件或目录的名称.

  • 这只过滤`.`和`..`,而不过滤其他目录. (2认同)
  • @Prince:通常在手册页上有相关功能的链接.通常值得点击以获得完整性. (2认同)

Sta*_*eyD 18

foreach(glob('directory/*', GLOB_ONLYDIR) as $dir) {
    $dir = str_replace('directory/', '', $dir);
    echo $dir;
}
Run Code Online (Sandbox Code Playgroud)

您可以使用GLOB_ONLYDIR简单地使用glob,然后过滤生成的目录


phi*_*hag 8

function scandir_nofolders($d) {
   return array_filter(scandir($d), function ($f) use($d) {
       return ! is_dir($d . DIRECTORY_SEPARATOR . $f);
   });
}
Run Code Online (Sandbox Code Playgroud)

这个函数返回一个你可以迭代或存储在某个地方的数组,这是99.37%的所有程序员都opendir想要的.


T.T*_*dua 6

仅列出文件夹(目录):

<?php
$Mydir = ''; ### OR MAKE IT 'yourdirectory/';

foreach(glob($Mydir.'*', GLOB_ONLYDIR) as $dir) {
    $dir = str_replace($Mydir, '', $dir);
    echo $dir;
}
?>
Run Code Online (Sandbox Code Playgroud)