Currently Browsing: Home » Directory Trees With PHP And jQuery

The Importance of Colors and Contrast »

« JQuery Drop Down Menu

Directory Trees With PHP And jQuery

By Karthik Viswanathan

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" "www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="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" class="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="/img/spacer.gif"> 

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 class=\"".$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 class=\"".$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: javascript, php, tutorial

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.

  • RSS
  • Tweet this!
  • Delicious
  • Facebook
  • DFloat
  • DMoo
  • E-mail

45 Responses to “Directory Trees With PHP And jQuery”

  1. spacer Tony Miller says:
    Thu 19 February, 2009 at 06:28:15

    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: 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.

    Reply
  2. spacer Karthik Viswanathan says:
    Thu 19 February, 2009 at 10:47:24

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

    Reply
  3. spacer OrganizedFellow says:
    Thu 19 February, 2009 at 22:41:03

    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:
    40

    Line 40=
    foreach ($queue as $file){

    Reply
  4. spacer Karthik Viswanathan says:
    Fri 20 February, 2009 at 00:29:16

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

    Reply
  5. spacer Patrick Lin says:
    Fri 20 February, 2009 at 09:13:17

    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: 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 server.flowoflogic.com/directory-trees-fixed/

    Reply
  6. spacer Karthik Viswanathan says:
    Fri 20 February, 2009 at 21:16:01

    @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)))
    Reply
  7. spacer NikBlack says:
    Sat 21 February, 2009 at 06:54:57

    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.

    Reply
  8. spacer antonio says:
    Mon 23 February, 2009 at 06:17:30

    It’s great!

    Reply
  9. spacer JDStraughan says:
    Mon 2 March, 2009 at 08:22:13

    Added to tutlist.com

    Reply
  10. spacer smkn says:
    Wed 8 April, 2009 at 20:48:40

    Hallo!
    It’s Very wonderful!

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

    Reply
    • spacer Karthik Viswanathan says:
      Thu 9 April, 2009 at 17:42:07

      @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!

      Reply
  11. spacer pfwd says:
    Mon 15 June, 2009 at 00:45:36

    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.

    Reply
  12. spacer seeal says:
    Mon 20 July, 2009 at 17:23:36

    It’s great! spacer

    Reply
  13. spacer danny says:
    Mon 23 November, 2009 at 10:03:53

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

    Reply
  14. spacer SM says:
    Wed 17 February, 2010 at 03:59:45

    Great plugin. Thanks

    Reply
  15. spacer aaron says:
    Thu 18 March, 2010 at 03:13:45

    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;

    Reply
    • spacer Praxis says:
      Mon 12 July, 2010 at 11:30:28

      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

      Reply
  16. spacer Eomm says:
    Sun 26 December, 2010 at 17:20:25

    i’ve made this inspired by this article
    miorepository.altervista.org/pj/RepoTree/

    Reply
  17. spacer donal says:
    Sat 26 March, 2011 at 14:11:47

    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.

    Reply
  18. spacer Anupam says:
    Sun 1 May, 2011 at 06:46:11

    nice, quick and easy, thanks

    Reply
  19. spacer syed adeel ali says:
    Mon 2 May, 2011 at 11:47:06

    this is so nice thnx

    Reply

  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

Click here to cancel reply.

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

gipoco.com is neither affiliated with the authors of this page nor responsible for its contents. This is a safe-cache copy of the original web site.