Php get list of folders in directory

How can I get all sub-directories of a given directory without files, .(current directory) or ..(parent directory) and then use each directory in a function?

Mohammed H

6,65916 gold badges77 silver badges125 bronze badges

asked Mar 26, 2010 at 14:55

Option 1:

You can use glob() with the GLOB_ONLYDIR option.

Option 2:

Another option is to use array_filter to filter the list of directories. However, note that the code below will skip valid directories with periods in their name like .config.

$dirs = array_filter(glob('*'), 'is_dir');
print_r($dirs);

Php get list of folders in directory

Pikamander2

6,3333 gold badges42 silver badges63 bronze badges

answered Mar 26, 2010 at 14:58

ghostdog74ghostdog74

313k55 gold badges252 silver badges339 bronze badges

7

Here is how you can retrieve only directories with GLOB:

$directories = glob($somePath . '/*' , GLOB_ONLYDIR);

answered Jun 9, 2010 at 13:44

Php get list of folders in directory

CoreusCoreus

4,9873 gold badges34 silver badges46 bronze badges

4

The Spl DirectoryIterator class provides a simple interface for viewing the contents of filesystem directories.

$dir = new DirectoryIterator($path);
foreach ($dir as $fileinfo) {
    if ($fileinfo->isDir() && !$fileinfo->isDot()) {
        echo $fileinfo->getFilename().'<br>';
    }
}

Php get list of folders in directory

answered Oct 4, 2013 at 10:14

stlocstloc

1,4581 gold badge16 silver badges26 bronze badges

0

Almost the same as in your previous question:

$iterator = new RecursiveIteratorIterator(
                new RecursiveDirectoryIterator($yourStartingPath), 
            RecursiveIteratorIterator::SELF_FIRST);

foreach($iterator as $file) {
    if($file->isDir()) {
        echo strtoupper($file->getRealpath()), PHP_EOL;
    }
}

Replace strtoupper with your desired function.

answered Mar 26, 2010 at 15:11

Php get list of folders in directory

GordonGordon

307k72 gold badges526 silver badges551 bronze badges

3

Try this code:

<?php
$path = '/var/www/html/project/somefolder';

$dirs = array();

// directory handle
$dir = dir($path);

while (false !== ($entry = $dir->read())) {
    if ($entry != '.' && $entry != '..') {
       if (is_dir($path . '/' .$entry)) {
            $dirs[] = $entry; 
       }
    }
}

echo "<pre>"; print_r($dirs); exit;

answered Nov 6, 2015 at 7:11

keyur0517keyur0517

852 silver badges6 bronze badges

In Array:

function expandDirectoriesMatrix($base_dir, $level = 0) {
    $directories = array();
    foreach(scandir($base_dir) as $file) {
        if($file == '.' || $file == '..') continue;
        $dir = $base_dir.DIRECTORY_SEPARATOR.$file;
        if(is_dir($dir)) {
            $directories[]= array(
                    'level' => $level
                    'name' => $file,
                    'path' => $dir,
                    'children' => expandDirectoriesMatrix($dir, $level +1)
            );
        }
    }
    return $directories;
}

//access:

$dir = '/var/www/';
$directories = expandDirectoriesMatrix($dir);

echo $directories[0]['level']                // 0
echo $directories[0]['name']                 // pathA
echo $directories[0]['path']                 // /var/www/pathA
echo $directories[0]['children'][0]['name']  // subPathA1
echo $directories[0]['children'][0]['level'] // 1
echo $directories[0]['children'][1]['name']  // subPathA2
echo $directories[0]['children'][1]['level'] // 1

Example to show all:

function showDirectories($list, $parent = array())
{
    foreach ($list as $directory){
        $parent_name = count($parent) ? " parent: ({$parent['name']}" : '';
        $prefix = str_repeat('-', $directory['level']);
        echo "$prefix {$directory['name']} $parent_name <br/>";  // <-----------
        if(count($directory['children'])){
            // list the children directories
            showDirectories($directory['children'], $directory);
        }
    }
}

showDirectories($directories);

// pathA
// - subPathA1 (parent: pathA)
// -- subsubPathA11 (parent: subPathA1)
// - subPathA2 
// pathB
// pathC

answered Mar 9, 2017 at 10:24

Php get list of folders in directory

You can try this function (PHP 7 required)

function getDirectories(string $path) : array
{
    $directories = [];
    $items = scandir($path);
    foreach ($items as $item) {
        if($item == '..' || $item == '.')
            continue;
        if(is_dir($path.'/'.$item))
            $directories[] = $item;
    }
    return $directories;
}

answered Sep 12, 2016 at 9:44

Php get list of folders in directory

Jan-FokkeJan-Fokke

3,2591 gold badge21 silver badges44 bronze badges

Non-recursively List Only Directories

The only question that direct asked this has been erroneously closed, so I have to put it here.

It also gives the ability to filter directories.

/**
 * Copyright © 2020 Theodore R. Smith <https://www.phpexperts.pro/>
 * License: MIT
 *
 * @see https://stackoverflow.com/a/61168906/430062
 *
 * @param string $path
 * @param bool   $recursive Default: false
 * @param array  $filtered  Default: [., ..]
 * @return array
 */
function getDirs($path, $recursive = false, array $filtered = [])
{
    if (!is_dir($path)) {
        throw new RuntimeException("$path does not exist.");
    }

    $filtered += ['.', '..'];

    $dirs = [];
    $d = dir($path);
    while (($entry = $d->read()) !== false) {
        if (is_dir("$path/$entry") && !in_array($entry, $filtered)) {
            $dirs[] = $entry;

            if ($recursive) {
                $newDirs = getDirs("$path/$entry");
                foreach ($newDirs as $newDir) {
                    $dirs[] = "$entry/$newDir";
                }
            }
        }
    }

    return $dirs;
}

answered Apr 12, 2020 at 8:47

Theodore R. SmithTheodore R. Smith

20.9k12 gold badges60 silver badges89 bronze badges

<?php
    /*this will do what you asked for, it only returns the subdirectory names in a given
      path, and you can make hyperlinks and use them:
    */

    $yourStartingPath = "photos\\";
    $iterator = new RecursiveIteratorIterator( 
        new RecursiveDirectoryIterator($yourStartingPath),  
        RecursiveIteratorIterator::SELF_FIRST);

    foreach($iterator as $file) { 
        if($file->isDir()) { 
            $path = strtoupper($file->getRealpath()) ; 
            $path2 = PHP_EOL;
            $path3 = $path.$path2;

            $result = end(explode('/', $path3)); 

            echo "<br />". basename($result );
        } 
    } 

    /* best regards,
        Sanaan Barzinji
        Erbil
    */
?>

Php get list of folders in directory

answered Aug 4, 2012 at 7:41

Proper way

/**
 * Get all of the directories within a given directory.
 *
 * @param  string  $directory
 * @return array
 */
function directories($directory)
{
    $glob = glob($directory . '/*');

    if($glob === false)
    {
        return array();
    }

    return array_filter($glob, function($dir) {
        return is_dir($dir);
    });
}

Inspired by Laravel

answered Jun 1, 2016 at 22:55

MacbricMacbric

4724 silver badges10 bronze badges

1

The following recursive function returns an array with the full list of sub directories

function getSubDirectories($dir)
{
    $subDir = array();
    $directories = array_filter(glob($dir), 'is_dir');
    $subDir = array_merge($subDir, $directories);
    foreach ($directories as $directory) $subDir = array_merge($subDir, getSubDirectories($directory.'/*'));
    return $subDir;
}

Source: https://www.lucidar.me/en/web-dev/how-to-get-subdirectories-in-php/

answered Sep 21, 2018 at 4:33

Php get list of folders in directory

FifiFifi

3,0831 gold badge22 silver badges45 bronze badges

1

This is the one liner code:

 $sub_directories = array_map('basename', glob($directory_path . '/*', GLOB_ONLYDIR));

answered Jul 25, 2019 at 11:48

SultanSultan

5994 silver badges13 bronze badges

Find all PHP files recursively. The logic should be simple enough to tweak and it aims to be fast(er) by avoiding function calls.

function get_all_php_files($directory) {
    $directory_stack = array($directory);
    $ignored_filename = array(
        '.git' => true,
        '.svn' => true,
        '.hg' => true,
        'index.php' => true,
    );
    $file_list = array();
    while ($directory_stack) {
        $current_directory = array_shift($directory_stack);
        $files = scandir($current_directory);
        foreach ($files as $filename) {
            //  Skip all files/directories with:
            //      - A starting '.'
            //      - A starting '_'
            //      - Ignore 'index.php' files
            $pathname = $current_directory . DIRECTORY_SEPARATOR . $filename;
            if (isset($filename[0]) && (
                $filename[0] === '.' ||
                $filename[0] === '_' ||
                isset($ignored_filename[$filename])
            )) 
            {
                continue;
            }
            else if (is_dir($pathname) === TRUE) {
                $directory_stack[] = $pathname;
            } else if (pathinfo($pathname, PATHINFO_EXTENSION) === 'php') {
                $file_list[] = $pathname;
            }
        }
    }
    return $file_list;
}

answered Dec 7, 2016 at 9:54

Php get list of folders in directory

2

If you're looking for a recursive directory listing solutions. Use below code I hope it should help you.

<?php
/**
 * Function for recursive directory file list search as an array.
 *
 * @param mixed $dir Main Directory Path.
 *
 * @return array
 */
function listFolderFiles($dir)
{
    $fileInfo     = scandir($dir);
    $allFileLists = [];

    foreach ($fileInfo as $folder) {
        if ($folder !== '.' && $folder !== '..') {
            if (is_dir($dir . DIRECTORY_SEPARATOR . $folder) === true) {
                $allFileLists[$folder . '/'] = listFolderFiles($dir . DIRECTORY_SEPARATOR . $folder);
            } else {
                $allFileLists[$folder] = $folder;
            }
        }
    }

    return $allFileLists;
}//end listFolderFiles()


$dir = listFolderFiles('your searching directory path ex:-F:\xampp\htdocs\abc');
echo '<pre>';
print_r($dir);
echo '</pre>'

?>

answered May 27, 2017 at 18:05

FaisalFaisal

4,3832 gold badges39 silver badges49 bronze badges

Find all subfolders under a specified directory.

<?php
function scanDirAndSubdir($dir, &$fullDir = array()){
    $currentDir = scandir($dir);

    foreach ($currentDir as $key => $filename) {
        $realpath = realpath($dir . DIRECTORY_SEPARATOR . $filename);
        if (!is_dir($realpath) && $filename != "." && $filename != "..") {
            scanDirAndSubdir($realpath, $fullDir);
        } else {
            $fullDir[] = $realpath;
        }
    }

    return $fullDir;
}

var_dump(scanDirAndSubdir('C:/web2.0/'));

Sample :

array (size=4)
  0 => string 'C:/web2.0/config/' (length=17)
  1 => string 'C:/web2.0/js/' (length=13)
  2 => string 'C:/web2.0/mydir/' (length=16)
  3 => string 'C:/web2.0/myfile/' (length=17)

answered Nov 5, 2015 at 17:09

user9342572809user9342572809

11.7k4 gold badges45 silver badges70 bronze badges

3

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

you can esay and simply get list of file in folder in php. The scandir() function in PHP is an inbuilt function which is used to return an array of files and directories of the specified directory. The scandir() function lists the files and directories which are present inside a specified path.

How do I view a directory in PHP?

PHP scandir() Function $b = scandir($dir,1);

What is __ DIR __ in PHP?

The __DIR__ can be used to obtain the current code working directory. It has been introduced in PHP beginning from version 5.3. It is similar to using dirname(__FILE__). Usually, it is used to include other files that is present in an included file.

What is PHP glob?

The glob() function returns an array of filenames or directories matching a specified pattern.