问题
I would like to use opendir() to list only the folders in a particular folder (i.e. /www/site/). I would like to exclude files from the list as well at the '.' and '..' folders that appear on a linux folder listing. How would I go about doing this?
回答1:
Check out the PHP docs for readdir(). It includes an example for exactly this.
For completeness:
<?php
if ($handle = opendir('.')) {
$blacklist = array('.', '..', 'somedir', 'somefile.php');
while (false !== ($file = readdir($handle))) {
if (!in_array($file, $blacklist)) {
echo "$file\n";
}
}
closedir($handle);
}
?>
Simply change opendir('.')
to your directory, i.e. opendir('/www/sites/')
, and update $blacklist
to include the names of files or directory you do not wish to output.
回答2:
foreach(glob('directory/*', GLOB_ONLYDIR) as $dir) {
$dir = str_replace('directory/', '', $dir);
echo $dir;
}
You can use simply glob with GLOB_ONLYDIR and then filter resulted directories
回答3:
function scandir_nofolders($d) {
return array_filter(scandir($d), function ($f) use($d) {
return ! is_dir($d . DIRECTORY_SEPARATOR . $f);
});
}
This function returns an array you can iterate over or store somewhere, which is what 99.37% of all programmers using opendir
want.
回答4:
List only folders (Directories):
<?php
$Mydir = ''; ### OR MAKE IT 'yourdirectory/';
foreach(glob($Mydir.'*', GLOB_ONLYDIR) as $dir) {
$dir = str_replace($Mydir, '', $dir);
echo $dir;
}
?>
回答5:
Try this with glob('*')
function
<?php
$dirs = array_filter(glob('*'), 'is_dir');
$i = 1;
foreach ($dirs as $value) {
echo $i . '. <a href = "http://localhost/' . $value . '" target = "_blank">' . $value . '</a><br>';
$i++;
}
?>
Above code worked for me for list out folders in current directory and I further developed code to open each folder in a new tab in same browser. This is shows only directories.
回答6:
Can also be used in forms to create a Dropdown of Folder names (here it is the images folder). Ensures that a user uploading an image pushes it to the correct folder :-)
<select name="imgfolder">
<option value="genimage">General Image</option>
<?php
$Mydir = '../images/'; // use 'anydirectory_of_your_choice/';
foreach(glob($Mydir.'*', GLOB_ONLYDIR) as $dir) {
$dirname = basename($dir) ;
echo '<option value="' . $dirname . '">' . $dirname . '</option>' ;
}
?>
</select>
来源:https://stackoverflow.com/questions/6497833/php-opendir-to-list-folders-only