PHP opendir() to list folders only

后端 未结 6 1134
日久生厌
日久生厌 2020-12-14 18:58

I would like to use opendir() to list only the folders in a particular folder (i.e. /www/site/). I would like to exclude files from the list as well at the \'.\' and \'..\'

相关标签:
6条回答
  • 2020-12-14 19:09
    function scandir_nofolders($d) {
       return array_filter(scandir($d), function ($f) use($d) {
           return ! is_dir($d . DIRECTORY_SEPARATOR . $f);
       });
    }
    

    This function returns an array you can iterate over or store somewhere, which is what 99.37% of all programmers using opendir want.

    0 讨论(0)
  • 2020-12-14 19:13
    foreach(glob('directory/*', GLOB_ONLYDIR) as $dir) {
        $dir = str_replace('directory/', '', $dir);
        echo $dir;
    }
    

    You can use simply glob with GLOB_ONLYDIR and then filter resulted directories

    0 讨论(0)
  • 2020-12-14 19:13

    List only folders (Directories):

    <?php
    $Mydir = ''; ### OR MAKE IT 'yourdirectory/';
    
    foreach(glob($Mydir.'*', GLOB_ONLYDIR) as $dir) {
        $dir = str_replace($Mydir, '', $dir);
        echo $dir;
    }
    ?>
    
    0 讨论(0)
  • 2020-12-14 19:14

    Check out the PHP docs for readdir(). It includes an example for exactly this.

    For completeness:

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

    Simply change opendir('.') to your directory, i.e. opendir('/www/sites/'), and update $blacklist to include the names of files or directory you do not wish to output.

    0 讨论(0)
  • 2020-12-14 19:18

    Try this with glob('*') function

        <?php
        $dirs = array_filter(glob('*'), 'is_dir');
        $i = 1;
        foreach ($dirs as $value) {
            echo $i . '. &nbsp; <a href = "http://localhost/' . $value . '" target = "_blank">' . $value . '</a><br>';
            $i++;
        }
        ?>
    

    Above code worked for me for list out folders in current directory and I further developed code to open each folder in a new tab in same browser. This is shows only directories.

    0 讨论(0)
  • 2020-12-14 19:31

    Can also be used in forms to create a Dropdown of Folder names (here it is the images folder). Ensures that a user uploading an image pushes it to the correct folder :-)

    <select name="imgfolder">
        <option value="genimage">General Image</option>
        <?php
        $Mydir = '../images/'; //  use 'anydirectory_of_your_choice/';
    
        foreach(glob($Mydir.'*', GLOB_ONLYDIR) as $dir) {
        $dirname =  basename($dir) ;
        echo '<option value="' . $dirname . '">' . $dirname . '</option>'  ; 
        }
        ?>
        </select>
    
    0 讨论(0)
提交回复
热议问题