我想使用 opendir() 仅列出特定文件夹(即 /www/site/)中的文件夹。我也想在“。”从列表中排除文件。和 '..' 出现在 linux 文件夹列表中的文件夹。我该怎么做呢?
问问题
48586 次
6 回答
21
foreach(glob('directory/*', GLOB_ONLYDIR) as $dir) {
$dir = str_replace('directory/', '', $dir);
echo $dir;
}
您可以简单地将 glob 与 GLOB_ONLYDIR 一起使用,然后过滤结果目录
于 2013-02-05T13:08:17.020 回答
20
查看readdir() 的 PHP 文档。它包括一个例子。
为了完整性:
<?php
if ($handle = opendir('.')) {
$blacklist = array('.', '..', 'somedir', 'somefile.php');
while (false !== ($file = readdir($handle))) {
if (!in_array($file, $blacklist)) {
echo "$file\n";
}
}
closedir($handle);
}
?>
只需更改opendir('.')
您的目录,即opendir('/www/sites/')
,然后更新$blacklist
以包含您不希望输出的文件或目录的名称。
于 2011-06-27T19:25:10.313 回答
8
function scandir_nofolders($d) {
return array_filter(scandir($d), function ($f) use($d) {
return ! is_dir($d . DIRECTORY_SEPARATOR . $f);
});
}
这个函数返回一个数组,你可以迭代或存储在某个地方,这是 99.37% 的程序员opendir
想要的。
于 2011-06-27T19:27:40.833 回答
6
仅列出文件夹(目录):
<?php
$Mydir = ''; ### OR MAKE IT 'yourdirectory/';
foreach(glob($Mydir.'*', GLOB_ONLYDIR) as $dir) {
$dir = str_replace($Mydir, '', $dir);
echo $dir;
}
?>
于 2013-03-28T10:10:05.237 回答
3
glob('*')
用函数试试这个
<?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++;
}
?>
上面的代码为我列出了当前目录中的文件夹,我进一步开发了代码以在同一浏览器的新选项卡中打开每个文件夹。这仅显示目录。
于 2015-11-25T09:41:20.017 回答
2
也可以在表单中使用以创建文件夹名称的下拉列表(这里是图像文件夹)。确保上传图像的用户将其推送到正确的文件夹:-)
<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>
于 2015-11-30T22:19:39.720 回答