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.
- Provide a starting folder, initiate an Ajax request to retrieve the contents of the folder including sub folders and files.
- 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.
- Send the list element to the browser and jQuery will insert it into the page.
- 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.