我需要老年人帮助使用php制作根目录的下拉列表。我创建了差不多但有一个问题是没有获得根目录。
喜欢home / abc / all dir我想要
代码示例
<?
$dirs = array_filter(glob('/*'), 'is_dir'); //this code getting main root folders
print_r($dirs); // array showing root directory
?>
但我想从home / username获取所有目录 有可能吗?
答案 0 :(得分:0)
以下代码找到用户目录(与Windows,Mac和Linux兼容),然后递归echo
目录路径。
<?php
$dir = '';
if (strpos(php_uname(),"Linux") === 0) {
//linux
$dir = "/home/";
} else {
//windows and mac
$dir = "/users/";
}
$dir.=get_current_user();
$iterator = new DirectoryIterator($dir);
foreach ($iterator as $fileinfo) {
if ($fileinfo->isDir() && !$fileinfo->isDot()) {
echo $fileinfo->getPathName() . "\n";
// recursion goes here.
}
}
?>
AJAX方法
Ajax基本上只是一种与服务器通信而无需刷新的方式。下面的代码是什么延迟加载目录。因此,正如它所需要的那样,它将加载目录的下一次迭代。我相信这就是你想要的,因为从根本上打印一切都有点自杀。
<?php
function filterDirectories($dir) {
$myDirs = scandir($_POST['dir']);
foreach ($myDirs as $key => $myDir) {
$path = str_replace('//','/',$dir . '/' . $myDir);
if (!is_dir($path) || $myDir === "." || $myDir === "..") {
unset($myDirs[$key]);
} else {
$myDirs[$key] = $path;
}
}
return array_values($myDirs);
}
if (isset($_POST['dir'])) {
echo json_encode(filterDirectories($_POST['dir']));
die();
}
?>
<body>
<form>
<div id="selectContainer">
</div>
</form>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(function () {
"use strict";
var rootDir = "/";
function getDirectory(dir) {
$.post("#", {
dir : dir
}, function (data) {
var $select = $("<select>");
for (var i = 0, len = data.length; i < len; i++) {
$("<option>")
.text(data[i])
.attr('value',data[i])
.appendTo($select);
}
$("#selectContainer").append($select);
}, "json");
}
getDirectory(rootDir);
$("#selectContainer").on("change", "select", function () {
$(this).nextAll().remove();
getDirectory($(this).val());
});
});
</script>
答案 1 :(得分:0)
尽管对问题做了澄清,但我并不是100%确定以下是你的意思。我认为您希望将所有文件夹放在起始位置 - 在您的情况下/home/username
recursiveIterator
类对于此类任务非常有用。
/* The ROOT directory you wish to scan */
$dir = 'c:/wwwroot/images';
if( realpath( $dir ) ){
$dirs=array();
$dirItr=new RecursiveDirectoryIterator( realpath( $dir ), RecursiveDirectoryIterator::KEY_AS_PATHNAME );
foreach( new RecursiveIteratorIterator( $dirItr, RecursiveIteratorIterator::CHILD_FIRST ) as $file => $info ) {
if( $info->isDir() ) $dirs[]=realpath( $info->getPathName() );
}
echo '<pre>',print_r( $dirs, 1 ),'</pre>';
}