Directory Trees With PHP And jQuery
Posted by Karthik Viswanathan on Mon 16 February, 2009 at 15:07:31 · Tags: javascript, php, tutorial
Knowing where your files are is an important task. Every person who uses a computer usually likes to store their files in an organized manner.
A simple way to keep track of many files is to use a directory tree. A directory tree lists out files and directories so that it’s easy to find what you’re looking for.
In this tutorial, we will create a directory tree using PHP and jQuery. This tree will use the code found in my previous article: jQuery drop down menus.
If you haven’t yet read the previous article, please do so. Everything used in that tutorial will be used here.
View a Demo Download the Files
As a quick refresher, take a look at the HTML code for the jQuery drop down menu:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" dir="ltr" lang="en-US">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>jQuery Drop Down Menu</title>
<!-- CSS For The Menu -->
<link rel="stylesheet" href="style.css" />
</head>
<body>
<!-- Menu Start -->
<div id="jQ-menu">
<!-- Unordered List With Menu Goes Here -->
</div>
<!-- End Menu -->
<!-- Add jQuery From the Google AJAX Libraries -->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script>
<!-- jQuery Color Plugin -->
<script type="text/javascript" src="jquery.color.js"></script>
<!-- Import The jQuery Script -->
<script type="text/javascript" src="jMenu.js"></script>
</body>
</html>
We will use all three files – index.html, jMenu.js, and style.css – for our directory tree. Remember to rename index.html to index.php. The PHP that we create will go inside the #jQ-menu divider.
In order to create a directory tree, we can use recursion. To begin, let’s layout our code:
function createDir($path = './')
{
}
function printFile($file, $path)
{
}
function printSubDir($dir, $path)
{
}
createDir();
We will have three functions:
createDir($path)takes in a path (or defaults to the directory which the file is in) to the directory that it is making a list of. It uses bothprintFile($file, $path)andprintSubDir($dir, $path).printFile($file, $path)prints out a link in a<li>element using a given filename and path.printSubDir($dir, $path)takes in a directory and creates a sub-directory by callingcreateDir($path). This is where the recursion ofcreateDir($path)takes place.
We can start off with printFile($file, $path).
function printFile($file, $path)
{
echo "<li><a href=\"".$path.$file."\">$file</a></li>";
}
This method is straightforward. It creates a list element with a link to the given file.
Let’s move on to the printSubDir($dir, $path) function.
function printSubDir($dir, $path)
{
echo "<li><span class=\"toggle\">$dir</span>";
createDir($path.$dir."/");
echo "</li>";
}
This code is the most important part. It uses recursion so that our directory tree prints out all sub-directories.
- Line one prints a
.togglespan element that shows/hides the sub-directory on click. The format used here is what the jQuery drop down menu uses to create its effects. - This second statement is where the recursion takes place. A new call to
createDir($path)will take care of the elements in this sub-directory. - The last line prints an ending list element to finish off the sub-directory.
Now we can code the createDir($path) function.
We must first open up the directory to read out of.
function createDir($path = './')
{
if ($handle = opendir($path))
{
}
}
The above code also makes sure the directory is valid.
Now we can print out the start and end of an unordered list that will represent this directory:
function createDir($path = './')
{
if ($handle = opendir($path))
{
echo "<ul>";
echo "</ul>";
}
}
At this point, we can read in the filenames:
function createDir($path = './')
{
if ($handle = opendir($path))
{
echo "<ul>";
while (false !== ($file = readdir($handle)))
{
}
echo "</ul>";
}
}
Our $file variable holds the filename of the current file. If this filename is actually a directory, we must call the printSubDir($dir, $path) function. On the other hand, if it is just a file, we should call the printFile($file, $path) function:
function createDir($path = './')
{
if ($handle = opendir($path))
{
echo "<ul>";
while (false !== ($file = readdir($handle)))
{
if ( is_dir($path.$file) && $file != '.' && $file != '..' )
printSubDir($file, $path);
else if ($file != '.' && $file != '..')
printFile($file, $path);
}
echo "</ul>";
}
}
Our directory tree is now functional! Unfortunately, it looks a bit odd when sub-directories are placed after files in the list. We can fix this by creating an array which stores the files. Once we have printed out all the directories, we can move on to printing the files:
function createDir($path = './')
{
if ($handle = opendir($path))
{
echo "<ul>";
$queue = array();
while (false !== ($file = readdir($handle)))
{
if (is_dir($path.$file) && $file != '.' && $file !='..')
printSubDir($file, $path, $queue);
else if ($file != '.' && $file !='..')
$queue[] = $file;
}
printQueue($queue, $path);
echo "</ul>";
}
}
function printQueue($queue, $path)
{
foreach ($queue as $file)
{
printFile($file, $path);
}
}
function printFile($file, $path)
{
echo "<li><a href=\"".$path.$file."\">$file</a></li>";
}
function printSubDir($dir, $path)
{
echo "<li><span class=\"toggle\">$dir</span>";
createDir($path.$dir."/");
echo "</li>";
}
createDir();
And that’s it! If you would like to access a different directory that the one your file is in, specify the $path parameter for the createDir($path) function.




Tony Miller on Thu 19 February, 2009 says:
This is a great tutorial to learn the meachanics of linking jQuery to PHP and client to server. You might want to mention a more application-like file viewer that makes use of jQuery: http://abeautifulsite.net/notebook/58 It’s called jQuery File Tree, and has server side connector scripts written in almost any flavor of scripting language you might come across.
Karthik Viswanathan on Thu 19 February, 2009 says:
@Tony: The jQuery File Tree you have linked to is easy to use and highly customizable. I’ll try to integrate it into the post.
OrganizedFellow on Thu 19 February, 2009 says:
Has anyone tried this on a large folder group?
I embedded the stylesheet and javascript files. Dropped the index.php file into a testing directory, added some files and folders. It works well.
Then decided to drop it into the root of my local machine.
I get the following error:
Warning: Invalid argument supplied for foreach() in /home/*****/public_html/index.php on line 40
Line 40=
foreach ($queue as $file){
Karthik Viswanathan on Fri 20 February, 2009 says:
@OrganizedFellow: I placed this file in the root of my own server and did not obtain this error. However, the menu was not able to show everything as it ran out memory. Does anything appear when you view the file?
Patrick Lin on Fri 20 February, 2009 says:
Karthik,
One of the problems I have with this implementation is that on some servers it doesn’t come out in alphabetical order. I know on the servers we’re hosting LC and the demos on it comes out alphabetically, but it doesn’t on my personal server at home. Take a look: http://server.flowoflogic.com/directory-trees/.
To fix this, I created another array, $queuedir, and added the directories to it. Then I sorted the queues and modified printSubDir to use a foreach loop.
This is my end results:
createDir:
function createDir($path = '.') { if ($handle = opendir($path)) { echo "<ul>"; $queuedir = array(); $queuefile = array(); while (false !== ($file = readdir($handle))) { if (is_dir($path.$file) && $file != '.' && $file !='..') $queuedir[] = $file; else if ($file != '.' && $file !='..') $queuefile[] = $file; } sort($queuedir); sort($queuefile); printSubDir($queuedir, $path); printQueue($queuefile, $path); echo "</ul>"; } }and printSubDir:
function printSubDir($queue, $path) { foreach ($queue as $dir) { echo "<li><span class=\"toggle\">$dir</span>"; createDir($path.$dir."/"); echo "</li>"; } }and it works, as seen at http://server.flowoflogic.com/directory-trees-fixed/
Karthik Viswanathan on Fri 20 February, 2009 says:
@OrganizedFellow: After some experimenting, Patrick discovered the problem. If a directory only has folders in it,
$queuenever gets initialized. Thus, the foreach loop cannot execute. To fix this, add the following line:before the while loop:
NikBlack on Sat 21 February, 2009 says:
This code is too fragile and slow (the PHP, that is). You should really be using the built-in Iterators that are part of SPL to parse directories.
antonio on Mon 23 February, 2009 says:
It’s great!
JDStraughan on Mon 2 March, 2009 says:
Added to tutlist.com
smkn on Wed 8 April, 2009 says:
Hallo!
It’s Very wonderful!
I wanna introduce & redistribute(with Modification a few) this on my site.
What license is this?
Karthik Viswanathan on Thu 9 April, 2009 says:
@smkn: Thank you for the positive feedback. Please do not copy this exact article onto your own site, but you are free to present a modification. Make sure to link back to this page. Good luck!
pfwd on Mon 15 June, 2009 says:
Nice article.
Personally I don’t echo code directly in my php functions. Instead I assign the strings to a var like $html and return the var at then end of the function.
Then in the output logic I echo the function call like:
Echo display_something();
I’m not sure but I think its good practice to let the function handle the logic and output whatever is returned from the funtion call.
seeal on Mon 20 July, 2009 says:
It’s great!
danny on Mon 23 November, 2009 says:
Just what this php n00b was looking for. thanks a lot!