PHP: Display Files and Sub-directories of A Directory Recursively as A Tree

by Yang Yang on May 10, 2011

Given a directory, how to display the contents (directories and files under it) of it recursively and exhaustively? Here’s the code:

$dir = '/path/to/directory'; // without trailing slash, can be absolute paths such as '/home/jim/public_html' or relative paths such as 'samples'

getDirContents($dir);

function getDirContents($dir) {
	if (is_dir($dir)) {
		$dirs = explode('/', $dir);
		$last_dir = $dirs[count($dirs) - 1];
		echo '<strong>'.$last_dir.'</strong>';
	    if ($dh = opendir($dir)) {
	    	echo '<ul>';
	        while (($file = readdir($dh)) !== false) {
	        	if ($file == '.' || $file == '..') {} else {
		        	echo '<li>';
		        	if (is_dir($dir.'/'.$file)) {
		        		getDirContents($dir.'/'.$file);
		        	} else {
		        		echo $file;
		        	}
		        	echo '</li>';
	        	}
	        }
	        echo '</ul>';
	        closedir($dh);
	    }
	}
	return false;
}

Recursively, the function getDirContents() explores every entry in the directory. If the entry is a file, it simply prints it; if it is a directory, it opens another subroutine of itself to explore that directory; and so forth, until every branch and sub-branches, etc. are all printed out.

Subscribe to Kavoir: blog feed

You should also read:

Comments on this entry are closed.

Previous post:

Next post: