Listing All the Folders Subfolders and Files in a Directory Using PHP

Listing all the folders subfolders and files in a directory using php

function listFolderFiles($dir){
$ffs = scandir($dir);

unset($ffs[array_search('.', $ffs, true)]);
unset($ffs[array_search('..', $ffs, true)]);

// prevent empty ordered elements
if (count($ffs) < 1)
return;

echo '<ol>';
foreach($ffs as $ff){
echo '<li>'.$ff;
if(is_dir($dir.'/'.$ff)) listFolderFiles($dir.'/'.$ff);
echo '</li>';
}
echo '</ol>';
}

listFolderFiles('Main Dir');

List all the files and folders in a Directory with PHP recursive function

Get all the files and folders in a directory, don't call function when you have . or ...

Your code :

<?php
function getDirContents($dir, &$results = array()) {
$files = scandir($dir);

foreach ($files as $key => $value) {
$path = realpath($dir . DIRECTORY_SEPARATOR . $value);
if (!is_dir($path)) {
$results[] = $path;
} else if ($value != "." && $value != "..") {
getDirContents($path, $results);
$results[] = $path;
}
}

return $results;
}

var_dump(getDirContents('/xampp/htdocs/WORK'));

Output (example) :

array (size=12)
0 => string '/xampp/htdocs/WORK/iframe.html' (length=30)
1 => string '/xampp/htdocs/WORK/index.html' (length=29)
2 => string '/xampp/htdocs/WORK/js' (length=21)
3 => string '/xampp/htdocs/WORK/js/btwn.js' (length=29)
4 => string '/xampp/htdocs/WORK/js/qunit' (length=27)
5 => string '/xampp/htdocs/WORK/js/qunit/qunit.css' (length=37)
6 => string '/xampp/htdocs/WORK/js/qunit/qunit.js' (length=36)
7 => string '/xampp/htdocs/WORK/js/unit-test.js' (length=34)
8 => string '/xampp/htdocs/WORK/xxxxx.js' (length=30)
9 => string '/xampp/htdocs/WORK/plane.png' (length=28)
10 => string '/xampp/htdocs/WORK/qunit.html' (length=29)
11 => string '/xampp/htdocs/WORK/styles.less' (length=30)

How to list directories, sub-directories and all files in php

Use scandir to see all stuff in the directory and is_file to check if the item is file or next directory, if it is directory, repeat the same thing over and over.

So, this is completely new code.

function listIt($path) {
$items = scandir($path);

foreach($items as $item) {

// Ignore the . and .. folders
if($item != "." AND $item != "..") {
if (is_file($path . $item)) {
// this is the file
echo "-> " . $item . "<br>";
} else {
// this is the directory

// do the list it again!
echo "---> " . $item;
echo "<div style='padding-left: 10px'>";
listIt($path . $item . "/");
echo "</div>";
}
}
}
}

echo "<div style='padding-left: 10px'>";
listIt("/");
echo "</div>";

You can see the live demo here in my webserver, btw, I will keep this link just for a second

When you see the "->" it's an file and "-->" is a directory

The pure code with no HTML:

function listIt($path) {
$items = scandir($path);

foreach($items as $item) {
// Ignore the . and .. folders
if($item != "." AND $item != "..") {
if (is_file($path . $item)) {
// this is the file
// Code for file
} else {
// this is the directory
// do the list it again!
// Code for directory
listIt($path . $item . "/");
}
}
}
}

listIt("/");

the demo can take a while to load, it's a lot of items.

How to list all files in folders and sub-folders using scandir and display them as an option in select?

While the other answers are fine and correct, allow me to add my solution as well:

function dirToOptions($path = __DIR__, $level = 0) {
$items = scandir($path);
foreach($items as $item) {
// ignore items strating with a dot (= hidden or nav)
if (strpos($item, '.') === 0) {
continue;
}

$fullPath = $path . DIRECTORY_SEPARATOR . $item;
// add some whitespace to better mimic the file structure
$item = str_repeat(' ', $level * 3) . $item;
// file
if (is_file($fullPath)) {
echo "<option>$item</option>";
}
// dir
else if (is_dir($fullPath)) {
// immediatly close the optgroup to prevent (invalid) nested optgroups
echo "<optgroup label='$item'></optgroup>";
// recursive call to self to add the subitems
dirToOptions($fullPath, $level + 1);
}
}

}

echo '<select>';
dirToOptions();
echo '</select>';

It uses a recursive call to fetch the subitems. Note that I added some whitespace before each item to better mimic the file structure. Also I closed the optgroup immediatly, to prevent ending up with nested optgroup elements, which is invalid HTML.

PHP Get all subdirectories of a given directory

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 - reading folder, all subfolders, and files in subfolders

I think your issue comes from here :

while (false !== ($file = readdir($handle))) // it reads again the same directory as it did in the first while loop

Try to replace it with

if ($sub_handle = opendir($dir . $folder)) {
while (false !== ($file = readdir($sub_handle))) {
...
}
closedir($sub_handle);
}

Also, in your case, I would use php glob() function

See a working example for your case :

$dir = './inspections/';
if ($handle = opendir($dir)) {
$blacklist = array('.', '..', 'default', 'default.php', 'desc.txt');
while (false !== ($folder = readdir($handle))) {
if (!in_array($folder, $blacklist)) {
foreach (glob($dir . $folder . "/*.png") as $filename) {
echo "$filename was found !";
echo "\r\n";
}
}
}
closedir($handle);
}

Output :

./inspections/location_4/img_1.png was found !
./inspections/location_4/img_2.png was found !
./inspections/location_4/img_3.png was found !
./inspections/location_4/img_4.png was found !
./inspections/location_4/img_5.png was found !
./inspections/location_4/img_6.png was found !
./inspections/location_3/img_1.png was found !
./inspections/location_3/img_2.png was found !
./inspections/location_3/img_3.png was found !
./inspections/location_3/img_4.png was found !
./inspections/location_3/img_5.png was found !
./inspections/location_3/img_6.png was found !
./inspections/location_2/img_1.png was found !
./inspections/location_2/img_2.png was found !
./inspections/location_2/img_3.png was found !
./inspections/location_2/img_4.png was found !
./inspections/location_2/img_5.png was found !
./inspections/location_2/img_6.png was found !
./inspections/location_1/img_1.png was found !
./inspections/location_1/img_2.png was found !
./inspections/location_1/img_3.png was found !
./inspections/location_1/img_4.png was found !
./inspections/location_1/img_5.png was found !
./inspections/location_1/img_6.png was found !

EDIT

To loop in the /inspections/location1/thumbs/ directories, this would work :

foreach (glob($dir . $folder . "/thumbs/*.png") as $filename) {
echo "$filename was found !";
echo "\r\n";
}

RE-EDIT

To glob multiple folders with the glob() function, your code should look like :

foreach (glob($dir.$folder."{/thumbs/*.png,/*.png}", GLOB_BRACE) as $filename) {
echo "$filename was found !";
echo "\r\n";
}

List subfolders with number of files PHP

Using PHP recursive function you can get simple array for folders.

PHP

<?php
$array=array();
function getCount($path){
$count=0;
global $array;
//$count=count(glob($path."/*"));
foreach(new DirectoryIterator($path) as $fileInfo){
if($fileInfo->isDir()){
if($fileInfo->isDot()) continue;
if(array_key_exists($fileInfo->getFilename(),$array)){
$array[$fileInfo->getFilename()] = array(
'is_file_directory' => 'file',
'count' => getCount($fileInfo->getPathname())
);
}
else{
$array[$fileInfo->getFilename()] = array(
'is_file_directory' => 'directory',
'count' => getCount($fileInfo->getPathname())
);
}
}
else{
$array[$fileInfo->getFilename()] = array(
'is_file_directory' => 'file',
'count' => 0
);
$count++;
}
}
return $count;
}
?>

How to use : getCount('folder/inner_folder'); print_r($array);

Listing out files in PHP (ONLY the files) as links from all subdirectories of a directory

Try using glob():

<?php
foreach(glob('path-to/UPLOAD_FOLDER/*') as $subDirectory) {
foreach(glob($subDirectory'./*') as $file) {

// do what you want with file here... example:
$file_list .= $file.'<br>';
}
}
echo $file_list;
?>


Related Topics



Leave a reply



Submit