php directory lister function

here is a simple function that iterates a directory recursively and returns as array.

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
	function directory_map($source_dir, $top_level_only = FALSE)
	{	
		if ($fp = @opendir($source_dir))
		{	
		//DIRECTORY_SEPARATOR is a constant is different on different Server OS
			$source_dir = rtrim($source_dir, DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR;		
			$filedata = array(); //let grab all files n directorys into this array
			//readdire iterates all the files n folders and returns 
			while (FALSE !== ($file = readdir($fp)))
			{
				if (strncmp($file, '.', 1) == 0)
				{
					continue;//if file or dir name is only '.' ,hidden files we skip them 
				}
 
				if ($top_level_only == FALSE && @is_dir($source_dir.$file))
				{
					$temp_array = array();
					//if is directory call this function itself recursively
					$temp_array = directory_map($source_dir.$file.DIRECTORY_SEPARATOR);
 
					$filedata[$file] = $temp_array;
				}
				else
				{
					$filedata[] = $file;
				}
			}
 
			closedir($fp); //finally close the directory and unlock file or directory data
			return $filedata; //return as array
		}
	}
 
// __FILE__ is PHP constant that tells the present executing script
// dirname extracts the directory name from a given file contains
$present_directory_with_allfilesandfolder=directory_map(dirname(__FILE__));
$onlyonetopleveldata=directory_map(dirname(__FILE__),true);

Download Demo

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="" highlight="">