Implementing a folder tree view of your folders, sub-folders and files that display in an explorer like interface on a web page requires little programming, but it’s not that tough. Though there are complex plugin solutions to create folder tree view, this is an attempt to implement a simple folder tree with PHP and jQuery to create an AJAX file browser with few lines of code and without using any plugins.

These are the steps we would be following to create this folder tree.

  1. Provide a starting folder, initiate an Ajax request to retrieve the contents of the folder including sub folders and files.
  2. PHP code that reads the folder and creates an unordered list with the folder and file names, also sets class names for different extensions of files.
  3. Send the list element to the browser and jQuery will insert it into the page.
  4. Monitor the click events, and when the user clicks on a folder or file – send it to the server ( Goes to step 1 ).

So all we need is PHP code that reads the directory( folder ) and generates html unordered list, and few lines of jQuery that manages the tree view in the browser and CSS to beautify the output.

PHP code to read the folder and generate html list.

The PHP part is written as a class that will read the given path( directory path ) and returns html list. The constructor of the tree view class takes the path and stores the directory entries ( sub-folders and files ) in an array. Another method of the class generates the list, which will also set different class name for folders and file extensions, so that we can use different images via CSS to differentiate the files and folder.

class treeview {

	private $files;
	private $folder;
	
	function __construct( $path ) {
		
		$files = array();	
		
		if( file_exists( $path)) {
			if( $path[ strlen( $path ) - 1 ] ==  '/' )
				$this->folder = $path;
			else
				$this->folder = $path . '/';
			
			$this->dir = opendir( $path );
			while(( $file = readdir( $this->dir ) ) != false )
				$this->files[] = $file;
			closedir( $this->dir );
		}
	}

	function create_tree( ) {
			
		if( count( $this->files ) > 2 ) { /* First 2 entries are . and ..  -skip them */
			natcasesort( $this->files );
			$list = '<ul class="filetree" style="display: none;">';
			// Group folders first
			foreach( $this->files as $file ) {
				if( file_exists( $this->folder . $file ) && $file != '.' && $file != '..' && is_dir( $this->folder . $file )) {
					$list .= '<li class="folder collapsed"><a href="#" rel="' . htmlentities( $this->folder . $file ) . '/">' . htmlentities( $file ) . '</a></li>';
				}
			}
			// Group all files
			foreach( $this->files as $file ) {
				if( file_exists( $this->folder . $file ) && $file != '.' && $file != '..' && !is_dir( $this->folder . $file )) {
					$ext = preg_replace('/^.*\./', '', $file);
					$list .= '<li class="file ext_' . $ext . '"><a href="#" rel="' . htmlentities( $this->folder . $file ) . '">' . htmlentities( $file ) . '</a></li>';
				}
			}
			$list .= '</ul>';	
			return $list;
		}
	}
}

jQuery Folder Tree

Now lets take a look at the jQuery script that manages the folder tree in browser, all we need to do is to collapse and expand the folder when we click on a folder name. First we need a container ( div element ) that will hold the folder tree.

<div id="container"> </div>

Now we got the container, let us initiate the process of building the folder and files tree with jQuery. So the first basic step will be to send an Ajax request to our PHP script, which will send us a neat list of folder and files which we will insert it on the page.

$(document).ready( function() {

	getfilelist( $('#container') , 'Sample' );
	
	function getfilelist( cont, root ) {

		/* send an ajax request */
	$.post( 'Foldertree.php', { dir: root }, function( data ) {

			$( cont ).append( data ); /* append the data to the div */
			if( 'Sample' == root ) /* check for the first run */
				$( cont ).find('UL:hidden').show();
			else /* subsequent calls will slide the list with animation */
				$( cont ).find('UL:hidden').slideDown({ duration: 500, easing: null });
			
	});
	}

You can see, we pass the id of the div element, which is our container where the folder tree will be displayed. The function “getfilelist” will send an Ajax request and appends the data to the div element with given id.

Folder tree getfiles jQueryNow for the final part we need the jQuery that will manage the expanding and collapsing of the folder tree, we will also check if it is a folder or just a file and check if the folder is collapsed or expanded and accordingly we will initiate the Ajax request.

$( '#container' ).on('click', 'LI A', function() { /* monitor the click event on links */
	var entry = $(this).parent(); /* get the parent element of the link */
	
	if( entry.hasClass('folder') ) { /* check if it has folder as class name */
		if( entry.hasClass('collapsed') ) { /* check if it is collapsed */
					
			entry.find('UL').remove(); /* if there is any UL remove it */
			getfilelist( entry, escape( $(this).attr('rel') )); /* initiate Ajax request */
			entry.removeClass('collapsed').addClass('expanded'); /* mark it as expanded */
		}
		else { /* if it is expanded already */

			entry.find('UL').slideUp({ duration: 500, easing: null }); /* collapse it */
			entry.removeClass('expanded').addClass('collapsed'); /* mark it as collapsed */
		}
	} else { /* clicked on file */
		$( '#selected_file' ).text( "File:  " + $(this).attr( 'rel' )); 
	}
return false;
});

Now that is all with PHP and jQuery, What? do you expect more? Sorry to disappoint.

CSS code is pretty much a basic stuff that will make the folder tree visually pleasing. You can see the demo and download the Folder Tree with PHP and jQuery form here.

Demo

Download

Simple Folder tree with PHP and jQuery

11 thoughts on “Simple Folder tree with PHP and jQuery

  • at
    Permalink

    Hello! Very good contribution. What should I do to only lists the JPG and GIF images?

    Reply
  • at
    Permalink

    If Foldername has a “ä,ö,ü” in it, it fires an Warning like “count(): Parameter must be an array or an object that implements Countable” from Line “if( count( $this->files ) > 2 ) { /* First 2 entries are . and .. -skip them */”

    how can this be fixed?

    Reply
    • at
      Permalink

      folder names like this will be counted as separate names delimited with comma

      Reply
      • at
        Permalink

        I tested your tree. If there is no national character in the folder title and there is a national character in the file name of this folder, the file name is displayed correctly. If there is a national character in the folder name, an error occurs and the file is not displayed, even if there is no national character in its name. Each click on the folder title produces a new error message without closing the folder.
        After possibly fixing the error, could you make a version limited to directory titles? I turned off file display for cito, but the error still persists. When I click on the folder name, I would like to display its contents in a separate “iframe”. Regards.

        Reply
        • at
          Permalink

          I will try to update it with support for national characters. may not be able to do immediately. Thanks for notifying the issue

          Reply
  • at
    Permalink

    This is a really nice view. However, I am having difficulty using an actual path (ex: /home/user/logs/), as it seems to reread the same directory and print the same folders/files. Any way to specify an actual directory?

    Reply
    • at
      Permalink

      you have to provide the full path as parameter , try like this getfilelist( $(‘#container’) , ‘/home/user/logs/’ );

      Reply
  • at
    Permalink

    I applied your code for my internal (not public) application at work (non-profit organization), how do I give credit to your contribution? Can you provide an HTML snippet of a blurb to be posted on the webpage?
    Thanks,
    John

    Reply
  • at
    Permalink

    Hello, this is great!!

    I want to openthe file, can I do It??

    Very good job.

    Reply
    • at
      Permalink

      It can be done, we need to send the clicked file name to the server and use the following header in PHP to initiate the download of the file – header(‘Content-Disposition: attachment; filename=”‘.$file.'”‘);

      Reply

Leave a Reply to pelister Cancel reply

Your email address will not be published. Required fields are marked *