Loop through user's directory
The following code finds the user directory (compatible with Windows, Mac, and Linux) then recursively echo
's the directory paths.
<?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() . "
";
// recursion goes here.
}
}
?>
Looping through the entire System
The AJAX method
Ajax is basically just a way of communicating to a server without having to refresh. What the following code does it lazy loads directories. So, as it's needed, it will load the next iteration for directories. I believe this would be what you want because printing everything from the root is a bit suicidal.
<?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>