Simple Folder tree with PHP and jQuery

Written by pelister. Posted in PHP

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

1 Star2 Stars3 Stars4 Stars5 Stars (18 votes, average: 4.61 out of 5)
Loading...
pelister
3D modeler and Web designer. Founder of Techlister. Love to build sites using WordPress and Joomla. Interested in Astronomy, project member of SETI (Search for Extra Terrestrial Intelligence).

Tags: , , , , , , ,

Leave a comment

Techlister© - 2012