Get Folders with PHP Glob - Unlimited Levels Deep

Get folders with PHP glob - unlimited levels deep

If you want to recursively work on directories, you should take a look at the RecursiveDirectoryIterator.

$path = realpath('/etc');

$objects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path), RecursiveIteratorIterator::SELF_FIRST);
foreach($objects as $name => $object){
echo "$name\n";
}

How to echo all the folder names in a particular folder using php?

<?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

How to return instances of a specific folder name and its paths?

An exemple that works (in other words, there is probably a more elegant way to do it):

function myfunction($param) {
echo $param . PHP_EOL;
}

$path = realpath('/myrootpath');
$target = 'myfolder';

$objects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path),
RecursiveIteratorIterator::SELF_FIRST,
RecursiveIteratorIterator::CATCH_GET_CHILD);
foreach($objects as $name => $object){
if (preg_match('~^.+/' . $target .'(?=/\.$)~', $object, $match))
myfunction($match[0]);
}

Using php to create a Folder select list - including child folders?

/* FUNCTION: showDir
* DESCRIPTION: Creates a list options from all files, folders, and recursivly
* found files and subfolders. Echos all the options as they are retrieved
* EXAMPLE: showDir(".") */
function showDir( $dir , $subdir = 0 ) {
if ( !is_dir( $dir ) ) { return false; }

$scan = scandir( $dir );

foreach( $scan as $key => $val ) {
if ( $val[0] == "." ) { continue; }

if ( is_dir( $dir . "/" . $val ) ) {
echo "<option>" . str_repeat( "--", $subdir ) . $val . "</option>\n";

if ( $val[0] !="." ) {
showDir( $dir . "/" . $val , $subdir + 1 );
}
}
}

return true;
}


Related Topics



Leave a reply



Submit