Currently Browsing: Home » Directory Trees With PHP And jQuery

Directory Trees With PHP And jQuery

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 both printFile($file, $path) and printSubDir($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 calling createDir($path). This is where the recursion of createDir($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 .toggle span 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.

Tags: , ,

This entry was posted on Monday, February 16th, 2009 at 15:07:31. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

45 Responses to “Directory Trees With PHP And jQuery”

  1. Tony Miller 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.

  2. @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.

  3. 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){

  4. @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?

  5. Patrick Lin 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/

  6. @OrganizedFellow: After some experimenting, Patrick discovered the problem. If a directory only has folders in it, $queue never gets initialized. Thus, the foreach loop cannot execute. To fix this, add the following line:

    $queue = array();

    before the while loop:

    while (false !== ($file = readdir($handle)))
  7. NikBlack 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.

  8. smkn says:

    Hallo!
    It’s Very wonderful!

    I wanna introduce & redistribute(with Modification a few) this on my site.
    What license is this?

  9. pfwd 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.

  10. danny says:

    Just what this php n00b was looking for. thanks a lot!

  11. SM says:

    Great plugin. Thanks

  12. aaron says:

    the code below and a little more is echoed in my browser, i thought this might have somethign to do with the echo statement before but changing it has no affect. Could you help me out?

    “;
    $queuedir = array();
    $queuefile = array();

    while (false !== ($file = readdir($handle)))
    {
    if (is_dir($path.$file) && $file != ‘.’ && $file !=’..’)
    printSubDir($file, $path, $queue);
    else if ($file != ‘.’ && $file !=’..’)
    $queue[] = $file;

    • Praxis says:

      I am working with this script, but cannot point the directory anywhere other than the index.php location. If i read this right then i should be able to change this line
      function createDir($path = ‘./’)
      {
      if ($handle = opendir($path))
      {

      to this…

      function createDir($path = ‘C:/wamp/www/main’)
      {
      if ($handle = opendir($path))
      {

      Any suggestions would help. Thanks

  13. donal says:

    It might be helpful to add this to the printSubDir function

    function printSubDir($dir, $path)
    {
    if($dir!=’.svn’){
    echo “$dir”;
    createDir($path.$dir.”/”,’subdir’.$dir);
    echo “”;
    }
    }

    If your working on a solution stored in SVN the script outputs the hidden SVN folders.

  14. Anupam says:

    nice, quick and easy, thanks

  15. syed adeel ali says:

    this is so nice thnx

  1. Directory Trees With PHP And jQuery | Switch on the Code
  2. Links Feb 22-28 « Work That Web
  3. 20 Useful PHP Components & Tutorials for Everyday Project | Noupe
  4. blog.no-panic.at » links for 2009-03-03
  5. Daily Links | AndySowards.com :: Professional Web Design, Development, Programming, Hacks, Downloads, Math and being a Web 2.0 Hipster?
  6. 20 Useful PHP & jQuery Components & Tuts for Everyday Project | Noupe
  7. ITキヲスク | いま現在サーバの中にあるフォルダとファイルを、jQueryを使って表示させるPHP製ディレクトリツリー、配布します!
  8. 20 Useful PHP Components & Tutorials for Everyday Project | YABIBO.COM - YOUR WEB WORLD
  9. 25 New & Useful PHP Techniques & Tutorials
  10. Useful PHP & jQuery Components « Developer Suite
  11. Javascript ve css eklentileri | FaydalıWeb | Internetin Faydalı Yüzü
  12. 20 Useful PHP + jQuery Components & Tuts for Everyday Project | Dummies Garage V3
  13. 10款javascript treeview和sitemap插件 | 我爱WEB – 专注于WEB开发与前端技术
  14. 35 Really Useful PHP Tutorials And Development Techniques | Smashing Buzz
  15. 15+ Useful PHP & jQuery Components | WEBAXES.COM
  16. Useful PHP Techniques & Tutorials | php tutorial
  17. 25 New & Useful PHP Techniques & Tutorials « PIXEL SHOP
  18. 60 Awesome jQuery Tutorials | Web.Dtuts - Web Development Tutorials
  19. 75+ jQuery Plugins: Download Powerful and Elegent jQuery Plugins & Tutorials | jQuery | Graphic Design Junction
  20. web file viewer ASP/PHP e Website Directory Indexer | lo stanzino di EngiMedia
  21. 20 Useful PHP + jQuery Components & Tuts for Everyday Project « Simplification
  22. 15 jQuery & PHP Combination Plugins | jQuery4u
  23. 25 Useful PHP Techniques and Tutorials | Timesneed.com
  24. PHP & JQUERY « catatananda

Leave a Reply

Want to be notified when someone replies? Subscribe to this post's comment RSS feed.
Any field marked with a * is required.