Using Scandir() to Find Folders in a Directory (Php)

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 scandir -- search for files/directories

$a = new RegexIterator(
new RecursiveIteratorIterator(
new RecursiveDirectoryIterator('DIRECTORY HERE')
),
'/REGEX HERE/',
RegexIterator::MATCH
);

foreach ($a as $v) {
echo "$v\n"; //$v will be the filename
}

php using scandir to get folder contents

That's because of system entries . and .. which are pointers to 'current directory' and 'parent directory'. You'll need to filter them if you don't want to see them in your output.

You may want to filter your entries with is_file() - then . and .. would be skipped since they are actually directories (pointers to them)

Using scandir on array of directories

You're on the right track. There are a few changes you need to make though.

function test($dir = []) {
$list = [];
foreach($dir as $bar) {
$list[] = scandir($bar);
}
print_r($list);
}

As noted by @BrianPoole you need to move the $list out of the foreach loop. By having it in the loop, the array is reset with each iteration, resulting in the final array having one element.

In addition, the foreach loop as explained above by @TimCooper does not operate the same as in JavaScript. If you really want to access the keys, you can use the following syntax:

foreach($dir as $key => $bar)

You would then use either $dir[$key] or $bar to access the directory value.

Finally, array_push is an additional function call that in your case is not needed. By simply adding [] PHP will push the new value onto the end of the array.

scandir to only show folders, not files

The easiest and quickest will be glob with GLOB_ONLYDIR flag:

foreach(glob('../images/*', GLOB_ONLYDIR) as $dir) {
$dirname = basename($dir);
}

PHP scandir and relative path

The $directory variable is set wrong. If you want to go 2 directories up use dirname() like this:

$directory = dirname(__DIR__,2) . '/uploads';
$filelist = "";
$dircont = scandir($directory);

foreach($dircont AS $item) {
if(is_file($item) && $item[0]!='.')
$filelist .= '<a href="'.$item.'">'.$item.'</a>'."<br />\n";
}

echo $filelist;

You can read more about scandir there is a section on how to use it with urls if allow_url_fopen is enabled but this is mainly in local/development environment.

PHP scandir to find video files and not include subdirectories

You can try this way using glob() to find all the files in the directory /path/to/your/directory with a .mp4 file extension:

foreach (glob("/path/to/your/directory/*.mp4") as $filename) {
echo "$filename size " . filesize($filename) . "\n";
}

See Example :http://php.net/manual/en/function.glob.php

Exploring a file structure using php using scandir()

There is probably a better solution, but hopefully the following will be of some help.

 <?php
function getDirectory( $path = '.', $level = 0 ){

$ignore = array( 'cgi-bin', '.', '..' );
// Directories to ignore when listing output. Many hosts
// will deny PHP access to the cgi-bin.

$dh = @opendir( $path );
// Open the directory to the handle $dh

while( false !== ( $file = readdir( $dh ) ) ){
// Loop through the directory

if( !in_array( $file, $ignore ) ){
// Check that this file is not to be ignored

$spaces = str_repeat( ' ', ( $level * 4 ) );
// Just to add spacing to the list, to better
// show the directory tree.

if( is_dir( "$path/$file" ) ){
// Its a directory, so we need to keep reading down...

echo "<strong>$spaces -$file</strong><br />";
getDirectory( "$path/$file", ($level+1) );
// Re-call this same function but on a new directory.
// this is what makes function recursive.

} else {

//To list folders names only and not the files within comment out the following line.
echo "$spaces $file<br />.";
// Just print out the filename
}
}
}
closedir( $dh );
// Close the directory handle
}
getDirectory( "folder" );
// Get the current directory
?>


Related Topics



Leave a reply



Submit