29/10/2016 - PHP
Use example below to list all files and folders in a given folder to create a treeview. Outcome is always in alphabetical order. Example depends on Font Awesome to add list icons to the result.
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
You need to include https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css
in your header to get the result below with icons.
class TreeView
{
private $root;
public function __construct($path)
{
$this->root = $path;
}
public function getTree($path = null)
{
$path = $path ? $path : $this->root;
$folders = [];
$files = [];
foreach (scandir($path) as $node) {
if ($this->filter($node)) {
continue;
}
if (is_dir($path.'/'.$node)) {
$folders[$node] = self::getTree($path.'/'.$node);
} else {
$files[$node] = str_replace($this->root.'/', null, $path.'/'.$node);;
}
}
return array_merge($folders, $files);
}
private function filter($filename)
{
return in_array($filename, ['.', '..', 'index.php', '.htaccess']);
}
}
$treeView = new TreeView('../uploads/');
$tree = $treeView->getTree();
function printTree($tree)
{
if ($tree) {
echo '<ul class="fa-ul">';
foreach ($tree as $node => $sub) {
if (strstr($node, '.')) {
echo '<li><i class="fa-li fa fa-file-o" aria-hidden="true"></i>';
echo '<a href="download.php?'.$sub.'">'.$node.'</a>';
echo '</li>';
} else {
echo '<li><i class="fa-li fa fa-folder" aria-hidden="true"></i>'.$node.'</li>';
}
if (is_array($sub)) {
printTree($sub);
}
}
echo '</ul>';
}
}
printTree($tree);