List All the Files and Folders in a Directory With PHP Recursive Function

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)

PHP: List all files in a folder recursively and fast

You could use the RecursiveDirectoryIterator - but I doubt, it's faster than a simple recusive function.

$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator('/path/to/folder'));
foreach ($iterator as $file) {
if ($file->isDir()) continue;
$path = $file->getPathname();
}

Find all .php files in folder recursively

just add something like:

function listFolderFiles($dir){
$ffs = scandir($dir);
$i = 0;
$list = array();
foreach ( $ffs as $ff ){
if ( $ff != '.' && $ff != '..' ){
if ( strlen($ff)>=5 ) {
if ( substr($ff, -4) == '.php' ) {
$list[] = $ff;
//echo dirname($ff) . $ff . "<br/>";
echo $dir.'/'.$ff.'<br/>';
}
}
if( is_dir($dir.'/'.$ff) )
listFolderFiles($dir.'/'.$ff);
}
}
return $list;
}

$files = array();
$files = listFolderFiles(dirname(__FILE__));

PHP Recursive function: Get all files and directories within a directory and its sub-directories

Switch $path with your path, and this should work. The SPL contains all the classes required for recursive directory traversal, there is no need to roll your own.

<?php

$path = '.';
$result = array('files' => array(), 'directories' => array());

$DirectoryIterator = new RecursiveDirectoryIterator($path);
$IteratorIterator = new RecursiveIteratorIterator($DirectoryIterator, RecursiveIteratorIterator::SELF_FIRST);
foreach ($IteratorIterator as $file) {

$path = $file->getRealPath();
if ($file->isDir()) {
$result['directories'][] = $path;
} elseif ($file->isFile()) {
$result['files'][] = $path;
}

}

print_r($result);

For more information, consult the PHP documentation: RecursiveDirectoryIterator, RecursiveIteratorIterator & SplFileInfo are great starting points!

PHP - Listing all directories and sub-directories recursively in drop down menu

RecursiveDirectoryIterator should do the trick. Unfortunately, the documentation is not great, so here is an example:

$root = '/etc';

$iter = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($root, RecursiveDirectoryIterator::SKIP_DOTS),
RecursiveIteratorIterator::SELF_FIRST,
RecursiveIteratorIterator::CATCH_GET_CHILD // Ignore "Permission denied"
);

$paths = array($root);
foreach ($iter as $path => $dir) {
if ($dir->isDir()) {
$paths[] = $path;
}
}

print_r($paths);

This generates the following output on my computer:

Array
(
[0] => /etc
[1] => /etc/rc2.d
[2] => /etc/luarocks
...
[17] => /etc/php5
[18] => /etc/php5/apache2
[19] => /etc/php5/apache2/conf.d
[20] => /etc/php5/mods-available
[21] => /etc/php5/conf.d
[22] => /etc/php5/cli
[23] => /etc/php5/cli/conf.d
[24] => /etc/rc4.d
[25] => /etc/minicom
[26] => /etc/ufw
[27] => /etc/ufw/applications.d
...
[391] => /etc/firefox
[392] => /etc/firefox/pref
[393] => /etc/cron.d
)

How to recursively iterate through files in PHP?

PHP has the perfect solution for you built in.

Example

// Construct the iterator
$it = new RecursiveDirectoryIterator("/components");

// Loop through files
foreach(new RecursiveIteratorIterator($it) as $file) {
if ($file->getExtension() == 'html') {
echo $file;
}
}

Resources

  • DirectoryIterator - Manual

PHP scandir recursively

You can scan directory recursively in this way the target is your top most directory:

function scanDir($target) {

if(is_dir($target)){

$files = glob( $target . '*', GLOB_MARK ); //GLOB_MARK adds a slash to directories returned

foreach( $files as $file )
{
scanDir( $file );
}


}
}

You can adapt this function for your need easily.
For example if would use this to delete the directory and its content you could do:

function delete_files($target) {

if(is_dir($target)){

$files = glob( $target . '*', GLOB_MARK ); //GLOB_MARK adds a slash to directories returned

foreach( $files as $file )
{
delete_files( $file );
}

rmdir( $target );

} elseif(is_file($target)) {

unlink( $target );
}

You can not do this in the way you are doing.
The following function gets recursively all the directories, sub directories so deep as you want and the content of them:

function assetsMap($source_dir, $directory_depth = 0, $hidden = FALSE)
{
if ($fp = @opendir($source_dir))
{
$filedata = array();
$new_depth = $directory_depth - 1;
$source_dir = rtrim($source_dir, '/').'/';

while (FALSE !== ($file = readdir($fp)))
{
// Remove '.', '..', and hidden files [optional]
if ( ! trim($file, '.') OR ($hidden == FALSE && $file[0] == '.'))
{
continue;
}

if (($directory_depth < 1 OR $new_depth > 0) && @is_dir($source_dir.$file))
{
$filedata[$file] = assetsMap($source_dir.$file.'/', $new_depth, $hidden);
}
else
{
$filedata[] = $file;
}
}

closedir($fp);
return $filedata;
}
echo 'can not open dir';
return FALSE;
}

Pass your path to the function:

$path = 'elements/images/';
$filedata = assetsMap($path, $directory_depth = 5, $hidden = FALSE);

$filedata is than an array with all founded directories and sub directories with their content. This function lets you scan the directories structure ($directory_depth) so deep as you want as well get rid of all the boring hidden files (e.g. '.','..')

All you have to do now is to use the returned array, which is the complete tree structure, to arrange the data in your view as you like.

What you are trying to do is in fact a kind of file manager and as you know there are a lot of those in the wild, open source and free.

I hope this will help you and I wish you a merry Christmas.

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.



Related Topics



Leave a reply



Submit