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?
The scandir() function returns an array of files and directories of the specified directory.
Substitute dir /A:D. /B /S > FolderList. txt to produce a list of all folders and all subfolders of the directory. WARNING: This can take a while if you have a large directory.
The opendir() function opens a directory handle.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With