Page 1 of 1

Simple directory traverser Rate Topic: ****- 1 Votes

#1 Auzzie  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 43
  • View blog
  • Posts: 573
  • Joined: 20-January 09

Posted 26 January 2009 - 11:16 PM

The aim of this tutorial is to show you a basic understanding of looping and PHP's scandir() function to build a simple recursive function that outputs the names of files and directories within a specified folder.

A little bit about the scandir function
The name says it all, it scans the dir (directory), it takes upto 3 parameters,
  • The directory to be scanned (string)
  • Whether you want the directory to be sorted a-z or z-a (give the parameter a number that isnt a 0 for z-a, defaults a-z) (integer)
  • Context, best bet is to read up on streams for a better understanding (resource)

What the scandir function does is it takes a folder's path in as its first parameter, and any files or folders that is within that directory gets added into an array, including the well known . and ..

Right lets move onto making our directory traverser. First off, as it is nice and simple we will contain all of our code within one function so that it is re-usable, it is too small to need to create an entire class for it. Considering we will only need the first two parameters we will only make them within the function. To make things even easier we will give $sort a default value of 0 so that when we call scandir we can keep to the default sorting but change to reverse sorting if needed.
function traverseDir($folder, $sort = 0) {



The first thing we will want to do is compile our array of files and folders. All of the code from now on is placed within one if statement because if the scandir function fails then the rest of the function's code is pretty much useless so there would be no point in it.
What this next piece does is to store the result of scandir in to $contents, For those that don't know, by putting the at symbol (@) in front of a function call, if the function would normally cause an error to appear then @ silences that error, allowing you to give the user a nice clean, friendly error message rather then a PHP or MySQL error.

So going on the basis that our if statement didn't fail the next thing we need to do is to create an empty array that we will later use. Then we will create an array of acceptable file types.
	if($contents = @ scandir($folder, $sort)) {
			   $found = array();

		// Create an array of file types, modify as needed
		$extension = array('doc','pdf','txt','docx','rtf','gIf','jpeg','jpg','png','avi','zip','mpeg','xml','bmp');



Now it is time for some looping action, the main point of this function, to loop through the $contents array to grab the name of each file and directory. for this i chose to use a foreach loop, the first thing we do once we are in this loop is use the pathinfo() function which is quite a useful function as it takes a path as its parameter and it breaks the path down into directory, basename, extension and filename.
The next thing we will do is run two checks, the first is to see if the $info has an extension (which makes it a file, not a directory) and then to see if the extension that it does have is part of our valid file types array previously declared in $extension. If both of the checks come back true, then the file gets stored in the $found array.
Note: Because pathinfo() returns the result as an array the best way to do the first check is to run array_key_exists()
		foreach($contents as $temp) {
			$info = pathinfo($temp);
			if(array_key_exists('extension', $info) && in_array($info['extension'],$extension)) {
				$found[] = $temp;
			}
		}


Finally the last stage, we need to see if we did find any files in that directory, if there was we will call natcasesort() which will sort the array into alphanumeric order (ignoring case sensitivity) then all that is laft is one last foreach loop to print out the results and to close off the open tags.
		if($found) {
			natcasesort($found);
			foreach($found as $filename) {
				echo $filename . "<br />";
			}
		}
	}
}



Finally, the full code listing:
function BuildFileList($folder) {
	if($contents = @ scandir($folder)) {
		$found = array();
		$extension = array('doc','pdf','txt','docx','rtf','gIf','jpeg','jpg','png','avi','zip','mpeg','xml','bmp');
		foreach($contents as $temp) {
			$info = pathinfo($temp);
			if(array_key_exists('extension', $info) && in_array($info['extension'],$extension)) {
				$found[] = $temp;
			}
		}
		if($found) {
			natcasesort($found);
			foreach($found as $filename) {
				echo $filename . "<br />";
			}
		}
	}
}



Is This A Good Question/Topic? 0
  • +

Page 1 of 1