php-directory-listing

How-To: List folder contents with PHP

This script generates a list of all files in a directory using a PHP function to read the directory files starting with the underscore _ character, and then it outputs them into a JQuery styled accordion menu!

Here’s the JQ

$(document).ready(function(){
	$("li.child:visible").hide();
	$("li.parent").click(function(){
		if ($(this).children().hasClass("selected")) {
			$(this).children().removeClass('selected');
			$(this).next().toggle("slow");
			return false;
		}
		else {
			$(this).children().addClass('selected');
			$(this).next().load($(this).children().attr("href")).toggle("medium");
			return false;
		}
 
	});
});

Here’s the PHP

if ($handle = opendir('./'))
{
	while (false !== ($file = readdir ($handle)))
	{
		if (preg_match("/^\_/", $file))
		{
			$filename = preg_replace('/\_/', ' ', $file);
			echo '<li class="parent"><a href="\">'.$filename.'</a></li>';
			echo '<li class="child"></li>';
		}
	}
	closedir($handle);
}