Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP opendir() to list folders only

Tags:

php

opendir

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 '..' folders that appear on a linux folder listing. How would I go about doing this?

like image 295
Jeff Thomas Avatar asked Jun 27 '11 19:06

Jeff Thomas


People also ask

How do I get a list of files in a directory in PHP?

The scandir() function returns an array of files and directories of the specified directory.

How do I get a list of directories in a directory?

Substitute dir /A:D. /B /S > FolderList. txt to produce a list of all folders and all subfolders of the directory. WARNING: This can take a while if you have a large directory.

What is opendir in PHP?

The opendir() function opens a directory handle.


2 Answers

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

like image 58
StanleyD Avatar answered Oct 03 '22 14:10

StanleyD


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.

like image 30
Jason McCreary Avatar answered Oct 03 '22 15:10

Jason McCreary