List Contents of a Directory

Here’s a little function I use when I want to ability to let users pick a file from a list. Its very easy to use and can be used in many different ways.

Here’s an example of what you will see:

First, just add this function to your page.

If you do not know how to do this, just create a file named “functions.php” and include it to the top of all your pages. Then just paste this function inside that file.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
	function buildFiles($directory) {
 
		//open this directory
		$myDirectory = opendir($directory);
 
		//get each entry
		while($entryName = readdir($myDirectory)) {
			$dirArray[] = $entryName;
		}
 
		//close directory
		closedir($myDirectory);
 
		//count elements in array
		$indexCount = count($dirArray);
		//Print ("$indexCount files<br>\n");
 
		//sort 'em
		sort($dirArray);
 
		//put into a select menu
		$output .= "<select size=\"10\" name=\"filename\">\n";
		// loop through the array of files and print them all
		for($index=0; $index < $indexCount; $index++) {
			if (substr("$dirArray[$index]", 0, 1) != "."){ // don't list hidden files
				$output .= "<option>".$dirArray[$index]."</option>";
			}
		}
		$output .= "</select>\n";
 
		echo $output;
 
	}

 

Now just call the function like this:

1
<?PHP buildFiles($directory); ?>
 
 

11 Users Responded in " List Contents of a Directory "

aonebill said,  

Hello. All of us could discuss together this theme in more details!?

Daheng said,  

неплохой ресурс, все полностью устроило. буду пользоваться дальше.

Formasamara said,  

Отлично сделали, есть чему поучиться.

Evrodims said,  

Отлично сделали, и тематика подходящая. Автору респект.

Dubafikos said,  

Мне как журналисту понравилось наполнение, побольше бы таких.

Serialu said,  

Да, не ожидал что увижу сдесь столько интересного в комментах.

Hodikos said,  

Неплохое решение, только зачем столько рекламы.

GedaBriefefor said,  

where did you read this?

Clipartmag said,  

Тоже думаю добавить в закладки, интересный блог.

gazongmk said,  

I join. So happens. Let’s discuss this question.
It is very a pity to me, I can help nothing, but it is assured, that to you will help to find the correct decision. Do not despair.
You are not right. I can prove it.
Be not deceived in this respect.
I consider, that you are not right. I am assured. Let’s discuss it. Write to me in PM.

damelio tren said,  

I admire your quality that you put into your work. Please do continue with more like this.

Leave A Reply Here

  Username [*]

  Email Address [*]

  Website

Subscribes to this post comments updates

Please Note: All comments maybe under going moderation so there is no need to resubmit the comments. it will appeared when admin approved it, feel free to subscribes to the post comments rss to stay update