School Assignment? Project Due Tomorrow? Chat LIVE With A Programming Expert!

Welcome to Dream.In.Code
Become an Expert!

Join 309,234 Programmers for FREE! Get instant access to thousands of experts, tutorials, code snippets, and more! There are 2,756 people online right now. Registration is fast and FREE... Join Now!




Simple directory traverser

 
Reply to this topicStart new topic

> Simple directory traverser

Auzzie
Group Icon



post 26 Jan, 2009 - 10:16 PM
Post #1


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.
CODE

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.
CODE

    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()
CODE

        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.
CODE

        if($found) {
            natcasesort($found);
            foreach($found as $filename) {
                echo $filename . "<br />";
            }
        }
    }
}


Finally, the full code listing:
CODE

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 />";
            }
        }
    }
}
Go to the top of the page
+Quote Post


Register to Make This Ad Go Away!


Reply to this topicStart new topic
1 User(s) are reading this topic (1 Guests and 0 Anonymous Users)
0 Members:

 


Lo-Fi Version Time is now: 11/26/09 08:55AM

Live Help!

Be Social

Dream.In.Code RSS Feed Dream.In.Code LinkedIn Group Follow Us On Twitter Fan Us On Facebook

Tutorials

Programming

Web Development

Reference Sheets

Code Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month