I want to print the folder names in a particular folder. For example Folder 1,2,3 are in a folder named 'New' I want to print the folder names 1 2 3 using php. Is it possible ? is there any function in php to do that ? any kind of solutions or ideas are very much appreciated.
Asked
Active
Viewed 3,038 times
2
-
1http://stackoverflow.com/questions/608450/using-scandir-to-find-folders-in-a-directory-php – mgraph Jan 03 '12 at 13:34
-
@mgraph I have tried the above solution, but it did't worked as you can see there is no accepted answer..! – Bala Jan 03 '12 at 13:36
-
possible duplicate of [Get folders with PHP glob - unlimited levels deep](http://stackoverflow.com/questions/5769514/get-folders-with-php-glob-unlimited-levels-deep) – nikc.org Jan 03 '12 at 13:38
4 Answers
1
Here is some example code from php.net on the readdir() function:
<?php
if ($handle = opendir('.')) {
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != "..") {
echo "$entry\n";
}
}
closedir($handle);
}
?>
If you modify this code to check $entry with the is_dir() function, you can easily find your directories.

Jeremy Harris
- 24,318
- 13
- 79
- 133
1
<?php
// declare the folder
$ourDir = "/home/public_html/folderName";
// prepare to read directory contents
$ourDirList = @opendir($ourDir);
// loop through the items
while ($ourItem = readdir($ourDirList))
{
// check if it is a directory
if (is_dir($ourItem))
{
echo "directory: $ourItem <br />";
}
// check to see if it is a file
if (is_file($ourItem))
{
echo "file: $ourItem <br />";
}
}
closedir($ourDirList);
?>
This is to echo both folders and files in a Directory.

Jinath Sanjitha
- 108
- 1
- 2
- 6
1
<?php
$dir = "/etc/php5/";
// Open a known directory, and proceed to read its contents
if (is_dir($dir)) {
if ($dh = opendir($dir)) {
while (($file = readdir($dh)) !== false) {
echo "filename: $file : filetype: " . filetype($dir . $file) . "\n";
}
closedir($dh);
}
}
?>
credit to php.net
Extending this logic,
<?php
$dir = "/etc/php5/";
// Open a known directory, and proceed to read its contents
if (is_dir($dir)) {
if ($dh = opendir($dir)) {
while (($file = readdir($dh)) !== false) {
if(filetype($dir . $file) == 'dir') {
echo "filename: $file : filetype: " . filetype($dir . $file) . "\n";
}
}
closedir($dh);
}
}
?>
should echo all directories
The output on my local server is:
filename: . : filetype: dir
filename: .. : filetype: dir
filename: apache : filetype: dir
filename: etc : filetype: dir
filename: pranav : filetype: dir

Pranav Hosangadi
- 23,755
- 7
- 44
- 70
1
glob function can be used to fetch directories too.
<?php
$folders = glob('/',GLOB_ONLYDIR);
print_r($folders);
?>

Alireza
- 6,497
- 13
- 59
- 132