Clean Dynamic Directory Listing with PHP

This here is a quick couple of functions to dynamically display files from any given directory.

It allows you to display it is a nice format with/out the files extension.

Pretty simple, but comments/suggestions/ bugs are very much welcome!!

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
34
35
36
37
38
39
40
41
< ?php
 
	// DIRECTORY DISPLAY USING GLOB AND A CLEAN PATH OUTPUT.
	// IF ALL PERIMATORS ARE EMPTY WILL SCNA DEFAULT DIRECTORY
	// '$path'  =>  PATH TO DIRECOTRY TO SCAN
	// '$ext'   =>  FILES EXT,  IF YOU WANT OT ECLUDE IT,  OR ONLY SCAN FOR ONE TYPE OF FILE
	// '$start' =>  APPEND TO START OF OUTPUT LINE EG: '<li>' OR '<div class="list">'
	// '$end'   =>  APPEND TO END OF OUTPUT LINE EG: '</div>\n' OR '</li>\n' => DEFAULT '\n'
	function direcotryList($path = "./", $ext = NULL, $start = NULL, $end = "\n"){
		$output = "";
		$ignore = array(".","..","thumbs.db");
		foreach(glob($path ."*". $ext) as $file){
			if(is_file($file) and !in_array($file, $ignore)){
				$output .= $start . buildLink($file, $path, $ext) . $end;
			}
		}
	}
 
	// THIS FUNCTION WILL OUTPUT A CLEAN LINK.
	// BUILT FROM THE PREVIOUS FUNCTION.
	function buildLink($file, $path, $ext = NULL){
		$len1  = strlen($path);
		$len2  = strlen($file);
		$start = ($len1 - $len2);
		$ext   = ($start + strlen($ext));
		$file  = substr($link, $start, -$ext);
		$name  = str_replace(array("_","-"), array(" "," "), $file);
		$link = "<a href=\"{$file}\">". ucwords($name) ."</a>";
		return $link;
	}
 
	// EXAMPLES OF USE
	// OUTPUT SIMPLE LINKS OF ALL FILES IN THE CURRENT DIRECTORY.
	echo(direcotryList());
 
	// OUTPUT ALL JPG IMAGES IN DIVS
	$output  = "<div id=\"gallery\">\n";
	$output .= direcotryList("images/",".jpg","<div class=\"image\">","</div>","\n");
	$output .= "</div>\n\n";
	echo($output);
?>
This entry was posted in Code, fun, Technology, work and tagged , , , , . Bookmark the permalink.

6 Responses to Clean Dynamic Directory Listing with PHP

  1. Pingback: Sheldon Lendrum » Blog Archive » Disabling WordPress Auto-Save and Revision Saving

  2. Pingback: Sheldon Lendrum » Blog Archive » Displaying Ordered Directory Listings

  3. Pingback: Rss VURSAKnoktacom » Blog Arşivi » Links for 2008-08-11 [del.icio.us]

  4. Kelvin says:

    Thanks. I was searching and got the point for my new assignment.

  5. William says:

    I’m not having much luck with this script, although I’m sure it functions perfectly.

    I am getting
    “Notice: Undefined variable: link”

    I am also unsure of what to put as the path, I am on IIS7.

    Thanks

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">