PHP - Listing the contents of a directory

December 2016





With PHP, the contents of a directory and its subdirectories can be viewed. Here below is a recursive function, allowing you to browse directories and subdirectories and view the files:


function ScanDirectory($Directory){

  $MyDirectory = opendir($Directory) or die('Error');
	while($Entry = @readdir($MyDirectory)) {
		if(is_dir($Directory.'/'.$Entry)&& $Entry != '.' && $Entry != '..') {
                         echo '<ul>'.$Directory;
			ScanDirectory($Directory.'/'.$Entry);
                        echo '</ul>';
		}
		else {
			echo '<li>'.$Entry.'</li>';
                }
	}
  closedir($MyDirectory);
}

ScanDirectory('.');

Related :

This document entitled « PHP - Listing the contents of a directory » from CCM (ccm.net) is made available under the Creative Commons license. You can copy, modify copies of this page, under the conditions stipulated by the license, as this note appears clearly.