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;
				$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.



Simple Folder tree with PHP and jQuery


3D modeler and Web designer. Founder of Techlister. Love to build sites using Wordpress and Joomla. Interested in Astronomy.

12 thoughts on “Simple Folder tree with PHP and jQuery

  • Aug 2, 2019 at 6:12 am

    How to remove the Scroll Bar for both sides

    • Aug 2, 2019 at 7:38 am

      can try the css property
      overflow-y: hidden;
      overflow-y: hidden;

      for the div or list element, but that will hide the elements if the list is lengthy.

      • Aug 2, 2019 at 8:37 am

        k. I will try. One more help. if i select one file in the tree view then the file is open in a new tap. The file may be a pdf or ppt or image.

        • Aug 2, 2019 at 8:55 am

          I haven’t added the option of opening files in new tab, you can modify the code, with php header content disposition

          • Aug 2, 2019 at 9:01 am

            I dont have clear idea for javascript. In your code the script return the selected file name in ‘. Is there any possible way to save the selected file name in a variable

          • Aug 2, 2019 at 1:39 pm

            This is the line that prints the filename – $( ‘#selected_file’ ).text( “File: ” + $(this).attr( ‘rel’ ));
            you can store the value into a variable or send an ajax request to fetch the file and show the file in a new tab

  • Oct 15, 2019 at 10:18 am

    How can I list only files with a specific extension (i.e. .xml)?
    I tried:
    while(( $file = readdir( $this->dir ) ) != false )
    if extname(($file) === ‘.xml’){
    $this->files[] = $file;
    But that doesn’t work

  • Jan 14, 2020 at 4:39 pm

    Please, what needs to be changed in order to open a .pdf file

    • Jan 14, 2020 at 5:01 pm

      you have to send an ajax request when you click on a file and within php set header content-disposition to attachment, which will force the file to open or download in the browser.

  • Feb 21, 2020 at 2:31 pm

    where should i give path


Leave a Reply

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