Use example below to list all files and folders in a given folder to create a toggleable treeview. Outcome is always in alphabetical order.


Current structure


cloud
candidates
one
one1.xls
one2.pdf
three
two
a
two
info.txt
info.txt
info.rtf
logo.jpg
readme.txt
clients
one
one
one1.txt
one2.png
one3.doc
one4.docx
two
two1.rtf
readme.txt
employees
index.php
.htaccess

Code


PHP


class TreeView
{
private $root;

public function __construct($path)
{
$this->root = $path;
}

public function getTree()
{
return $this->createStructure($this->root, true);
}

private function createStructure($directory, $root)
{
$structure = $root ? '<ul class="treeview">' : '<ul>';

$nodes = $this->getNodes($directory);
foreach ($nodes as $node) {
$path = $directory.'/'.$node;
if (is_dir($path) ) {
$structure .= '<li class="treeview-folder">';
$structure .= '<span>'.$node.'</span>';
$structure .= self::createStructure($path, false);
$structure .= '</li>';
} else {
$path = str_replace($this->root.'/', null, $path);
$structure .= '<li class="treeview-file">';
$structure .= '<a href="download_cloud.php?'.$path.'">'.$node.'</a>';
$structure .= '</li>';
}
}

return $structure.'</ul>';
}

private function getNodes($directory = null)
{
$folders = [];
$files = [];

$nodes = scandir($directory);
foreach ($nodes as $node) {
if (!$this->exclude($node)) {
if (is_dir($directory.'/'.$node)) {
$folders[] = $node;
} else {
$files[] = $node;
}
}
}

return array_merge($folders, $files);
}

private function exclude($filename)
{
return in_array($filename, ['.', '..', 'index.php', '.htaccess', '.DS_Store']);
}
}

$treeView = new TreeView('cloud');
echo $treeView->getTree();

JS


$(document).ready(function() {
$('.treeview').find('ul').hide();

$('.treeview-folder span').click(function() {
$(this).parent().find('ul:first').toggle('medium');

if ($(this).parent().attr('className') == 'treeview-folder') {
return;
}
});
});

CSS


.treeview span:hover {
cursor: pointer;
}
.treeview-folder {
list-style-image: url('../images/icon_folder.png');
}
.treeview-file {
list-style-image: url('../images/icon_file.png');
}

Result