Download folder tree

Demo

Bookmark and Share

Download files

Download

Licensing

This script is licensed under LGPL. Commercial licenses are also available

PHP

This script requires that you have PHP support. I'm planning to implement support for other server side languages later on. If you like the script and wants to convert the code to JSP, ASP or similar, please do so. If you send me the new script(post@dhtmlgoodies.com), I will post the script on this website

Setup information

The tree is a PHP class. The first you have to do is to include the class file:
include("dhtmlgoodies_tree.class.php");
Then you create a object of the class like this:
$tree = new dhtmlgoodies_tree();

The next step is to add nodes to the tree. There are two methods to choose from in order to do this. The new method(added 2011) addToArrayAss accepts an array as only argument.

Example:
$tree->addToArrayAss(array(
  'id' => 1,
  'title' => "America",
  'parentId' => 0,
  'url' => "http://www.dhtmlgoodies.com",
  'target' => "_blank",
  'icon' => "images/dhtmlgoodies_sheet.gif",
  'onclick' => "alert('hello')"
  )
);

parentId, url, target, icon and onclick are optional parameters.

You can also add nodes with the addToArray() method. This method takes up to 7 arguments(ID, title, parent ID, url, target and icon). The last arguments(icon) and onclick are optional.

Example:
$tree->addToArray(1,"America",0,"");
$tree->addToArray(2,"USA",1,"");
$tree->addToArray(3,"Alabama",2,"http://www.domain.com","frmMain");
$tree->addToArray(4,"Alaska",2,"","frmMain");
$tree->addToArray(5,"Arizona",2,"","frmMain");
$tree->addToArray(6,"Arkansas",2,"","frmMain");
$tree->addToArray(7,"California",2,"","frmMain");
$tree->addToArray(8,"Colorado",2,"","frmMain",
  "images/dhtmlgoodies_sheet.gif","alert('id is 8')");

The 'ID' identifies the node in the tree, thus it have to be unique. Title is the title of the node in the tree while parent ID is used for child nodes to identify it's parent. Url and target are optional arguments. The target is typically used if you're dealing with a frameset and wants the url to be opened in another frame than where the tree is.

You can see in the example code above, that "USA" have ID=2 and parentID=1. "1" is a the unique identification of USA in the tree and the parentID refers to the parent node which is "America".

Root nodes doesn't have any parent ID(example: America)

Usually, you don't add these nodes manually as I have done here. The best approach is to get them from a database. Example:
$res = mysql_query("select ID,title,parentID,url from table_category") or die(mysql_error());
while($inf = mysql_fetch_array($res)){
  $tree->addToArrayAss(array(
    'id' => $inf["ID"],
    'title' = >$inf["title"],
    'parentId' => $inf["parentID"],
    'url' => $inf["url"],
    'target' => "_blank")
  );
}

When all the nodes has been added, you have to call the functions which outputs Javascript, CSS and the HTML to the browser:
$tree->writeCSS();
$tree->writeJavascript();
$tree->drawTree();

For more info see the example file(dhtmlgoodies_tree.html) in the downloadable zip file and open the file dhtmlgoodies_tree_index.html to see how it works in your browser.

Expand all/Collapse all

You have two javascript functions which you could use to expand or collapse all nodes. The name of these functions are:

  • expandAll()
  • collapseAll()

Comments

mailer
How can this script be used to view folders and files in a directory.
mailer at 08:31PM, 2011/05/19.
Admin comment
DHTMLGoodies
One suggestion:Use readdir to read the file system(See : http://no2.php.net/manual/en/function.readdir.php) and then add each entry to the tree:$tree->addToArrayAss(array( 'id' => $uniqueNo, 'title' => $file, 'parentId' => $parentId, 'url' => "somePage.php", 'target' => "_blank", 'icon' => "images/dhtmlgoodies_sheet.gif" ));
DHTMLGoodies at 06:39AM, 2011/05/20.
hvn
Please help me!!!when i've done this, my drop-down list is not displaying correctly. It looks like that:http://imageshack.us/photo/my-images/841/treebreake.jpg/I cant find a solution to solve a problem!Thanks in advance:-)
hvn at 04:31PM, 2011/06/09.
mayeek
Hello!I don't know why, but function:$tree->writeCSS();$tree->writeJavascript();$tree->drawTree();Don't do anything! :/My list look's like this:Please help!
mayeek at 12:02PM, 2011/06/22.
mayeek
I change the dhtmlgoodies-tree.html to dhtmlgoodies-tree.php and it's works!Greate solution for my problem!
mayeek at 08:13AM, 2011/07/13.
Joel Penner
<a href="#comment731">mayeek wrote:</a>I change the dhtmlgoodies-tree.html to dhtmlgoodies-tree.php and it's works!Greate solution for my problem!
Thanks!!
Joel Penner at 11:01PM, 2011/08/06.
Andi
Nice tutorial
Andi at 07:55AM, 2011/10/31.
Ryan
Can this be used with a webservice call and jsp?
Ryan at 09:23AM, 2011/11/22.
vaibhav
Thanks for your ready made classes for folder tree structure creation .. i did this job in a second as assign my parameter to it..
vaibhav at 09:58AM, 2012/03/30.
emi
Just change from .html to .php, that's all fix the matters. And also, some script like "<?" need to change to "<?php"
emi at 08:53AM, 2012/06/12.
BlueChip
I didn't like the way that an open folder would close if I clicked on the folder-title, so I modified expandNode() accordingly:

function expandNode(e,inputNode)
{
if(initExpandedNodes.length==0)initExpandedNodes=",";
if(!inputNode)inputNode = this;

if(inputNode.tagName.toLowerCase()!='img') {
inputNode = inputNode.parentNode.getElementsByTagName('IMG')[0];
openOnly = true;
} else {
openOnly = false;
}

var inputId = inputNode.id.replace(/[^\d]/g,'');

var parentUl = inputNode.parentNode;
var subUl = parentUl.getElementsByTagName('UL');

if(subUl.length==0)return;
if( (subUl[0].style.display=='' || subUl[0].style.display=='none')) {
subUl[0].style.display = 'block';
inputNode.src = minusNode;
initExpandedNodes = initExpandedNodes.replace(',' + inputId+',',',');
initExpandedNodes = initExpandedNodes + inputId + ',';

} else if (!openOnly) {
subUl[0].style.display = '';
inputNode.src = plusNode;
initExpandedNodes = initExpandedNodes.replace(','+inputId+',',',');
}
Set_Cookie(nameOfCookie,initExpandedNodes,60);
}
BlueChip at 03:13AM, 2012/08/07.
BlueChip
Display a sorted directory tree whereby each directory is a web-page

[code]
<!--

index.html: Creates Tree on the left - Pages on the right

: tree.php is THIS file
: FrontPage.php is the name of the default page (on the right)
: the name/id "frDisp" cannot be changed - unless you know what you are doing
: The default width of the tree frame is 200 pixels
: See http://www.w3schools.com/tags/tag_frameset.asp for further details

<html>
<frameset cols="200,*" TOPMARGIN="0" LEFTMARGIN="0" MARGINHEIGHT="0" MARGINWIDTH="0">
<frame src="tree.php" name="tree" id="tree" frameborder="0" marginwidth="5" marginheight="0" scrolling="auto">
<frame src="FrontPage.php" name="frDisp" id="frDisp" frameborder="0" marginwidth="5" marginheight="0">
</frameset>
</html>
-->

<?php //========================================================================

// You will need to edit this to point to the right directory
include("WWW/tree/dhtmlgoodies_tree.class.php");

// Global variables
$id = 0;
$tree = array();

//-------------------------------------------------------------------
// Call this to build a tree from your directory structure
// Eg. doDir("/path/to/root_folder")
function doDir ($root)
{
global $id, $tree;

$tree = new dhtmlgoodies_tree(); // Creating new tree object
$id = 1; // Initialise the internal ID counter

// Create the "root" folder
$tree->addToArrayAss( array(
'parentId' => 0,

'id' => $id,
'title' => "Front Cover",
'url' => "FrontPage.php",
'target' => "frDisp",
'icon' => "WWW/tree/folder.png",
'onclick' => "" //"alert('hello')"
) );

// Add all the other folders under it
$rv = Dir_rec($root, $id, 0);

// Display the tree
$tree->writeCSS();
$tree->writeJavascript();
$tree->drawTree();

// Will return false iff root is invalid ...otherwise returns true
return $rv;
}

//-------------------------------------------------------------------
// This is an internal function - do NOT call it directly; use doDir()
// $depth is not currently used, but may be used later to restrict recursion
function Dir_rec ($path, $parent, $depth)
{
global $id, $tree;

// Make sure we can open the directory - or just get on and fail now!
if ( ($dh = @opendir($path)) == false ) return(false) ;

$list = array(); // somewhere to store a directory listing

// Collect directory listing
while ( ($file = readdir($dh)) !== false )
{
// Ignore some stuff
if ( !is_dir( "$path/$file" ) ) continue ; // Ignore non-directories
if ( $file[0] == "." ) continue ; // Ignore "dotfiles" (hidden files)
if ( $file[0] == "-" ) continue ; // Ignore names starting with "-"
if ( $file == "WWW" ) continue ; // Ignore the WWW directory (cgi-bin)

array_push($list, $file);
}

// Sort the list alphabetically
asort($list);

// Iterate & Recurse through the sorted directory listing
foreach ($list as $file) {
$id++;

$tree->addToArrayAss( array(
'parentId' => $parent,

'id' => $id,
'title' => $file,
'url' => $path . "/" . $file,
'target' => "frDisp",
'icon' => "WWW/tree/folder.png",
'onclick' => "",//alert('hello')"
) );

// If it's a directory, recurse (Ie. depth first)
Dir_rec( $path.'/'.$file, $id, $depth+1) ;
}

closedir($dh);
return(true);
}

//==============================================================================
?>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>The Show</title>

<!-- This is the styling for the folder names -->
<style type="text/css">
a {
text-decoration:none;
font-family:arial;
font-size:1em;
}
</style>
</head>

<body>
<!-- The username is taken from "HTTP Basic Authentication" and can be safely removed -->
<b>User: <?=$_SERVER['PHP_AUTH_USER']?></b><br />

<!-- These buttons will expand/collapse the tree - remove if not required -->
Tree: <button type="button" onclick="expandAll();return false">Show</button>
<button type="button" onclick="collapseAll();return false">Hide</button>

<!-- This will create and display the folder tree -->
<?php doDir("."); ?>
</body>
</html>
[/code]
BlueChip at 10:21PM, 2012/08/19.
bujashaka
I got it working but i don't like it opening all links in new window/tab. How to prevent this?
bujashaka at 03:24PM, 2015/07/23.
Joe
What if I dont want to be able to click on name to expand folder tree? I only want to be able to just to click on plus and minus icon to expand instead?
Joe at 10:32AM, 2016/07/22.

Post your comment

Don't have an avatar? Create one at Gravatar.com.

Unable to save captcha-image.