Notes

Tip

A URL can be used as a
filename with this function if the fopen wrappers have been enabled.
See fopen() for more details on how to specify the
filename. See the Supported Protocols and Wrappers for links to information
about what abilities the various wrappers have, notes on their usage,
and information on any predefined variables they may
provide.

Needed something that could return the contents of single or multiple directories, recursively or non-recursively,for all files or specified file extensions that would beaccessible easily from any scope or script.

Usage:scanDir::scan(path(s):string|array, [file_extensions:string|array], [subfolders?:true|false]);<?php//Scan a single directory for all files, no sub-directories$files = scanDir::scan('D:\Websites\temp');

Care needed going from PHP 5.3 to 5.4, as the constant SCANDIR_SORT_DESCENDING is only defined from 5.4.

I had previously been using literal, i.e. scandir($targetDir,2) in 5.3, but this did not give desired result in 5.4 (Ascending is default). However when I used SCANDIR_SORT_DESCENDING which is not defined in 5.3, on my web host (still on 5.3) I got error - second argument assumed to be a string.

Here's a simple little scandir() function that can pick a random photo (jpg only so far) and dislpay it. This also goes through an exclusion list and doesn't store anything you don't want to display. Use as you wish

This method would leave the file system vulnerable using ../ for the ?dir= A person could navigate any readable file system simply by adding ../ enough times to get back to the root of the drive.

On a proper secure system this might not matter, however for less secure file systems where the web user(apache user) can at least read most files, or on multi-user web servers this could lead to potential security risks.

Adding a check to see if ../ is in the $_GET["dir"] is one way to prevent this.

Note that scandir() will enforce alphanumerical sorting on the array it returns. If you wish to reduce CPU overhead by avoiding the sorting, or if you wish to obtain "natural filesystem order" - that is, the order in which the files are found while traversing the filesystem (usually the order in which they were written to the disk) - you need to go back to the PHP4 equivalent of opendir() + readdir().

If you have a folder with many files and/or subfolders, doing a recursive scandir will likely either slow down your application, or cause a high rise in RAM consumption due to the large size of the generated array.

To help with this, as well as to make processing of files in a folder easier, I wrote a function that reads a folder and its subfolders recursively, and calls a function upon each match.

Of course, because it is recursive, a folder with many levels of folders could potentially consume lots of memory, but then again, so can every other recursive scandir implementation here.

BTW, there's also the RecursiveDirectoryIterator SPL class:http://bg.php.net/manual/en/class.recursivedirectoryiterator.phpwhich, even if using the same approach, will most likely be faster and hold down deeper levels (because it works on the C level), but this one will always work, regardless of settings... even on PHP4.

Here is a function that parses your website's directory tree, similar to the scanDirectories function provided by fatpratmatt. However, this allows you to filter out all files except for those with specific extensions, in addition to allowing you to ignore entire directories, and also has a list of specific files to ignore. One last addition is that it allows you to use a regular expression to ignore another set of files.

I use this to walk the directory structure of my website, and to generate a sitemap.xml for Google sitemaps to index my site. This allows me to skip dev, data, library, etc. folders, and files that are not front end files.

The way it's written means you don't need to worry about excluding specific files at all unless they have the extension you are looking for (i.e. html or php files).

Back in the saddle of scandir I wrote this function for a function that I needed to seperate directories from files. Since I am still learning from my last example way below I would figure I would add it so it can be criticized.<?phpfunction dirlist($dir, $bool = "dirs"){$truedir = $dir;$dir = scandir($dir); if($bool == "files"){ // dynamic function based on second pram$direct = 'is_dir'; }elseif($bool == "dirs"){$direct = 'is_file'; } foreach($dir as $k => $v){ if(($direct($truedir.$dir[$k])) || $dir[$k] == '.' || $dir[$k] == '..' ){ unset($dir[$k]); } }$dir = array_values($dir); return $dir;}?><?phpprint_r(dirlist("../")); //confirm array of subdirectories

<?php/** * outputs all files and directories * recursively starting with the given * $base path. This function is a combination * of some of the other snips on the php.net site. * All are good but lacked one thing or another * that I needed like .htaccess * files get excluded with the one that checks to * see if the first character is a . and omits * that. * * @example rscandir(dirname(__FILE__).'/')); * @param string $base * @param array $omit * @param array $data * @return array */function rscandir($base='', &$data=array()) {

foreach($array as $value) : /* loop through the array at the level of the supplied $base */

if (is_dir($base.$value)) : /* if this is a directory */$data[] = $base.$value.'/'; /* add it to the $data array */$data = rscandir($base.$value.'/', $data); /* then make a recursive call with the current $value as the $base supplying the $data array to carry into the recursion */

elseif (is_file($base.$value)) : /* else if the current $value is a file */$data[] = $base.$value; /* just add the current $value to the $data array */

Bear in mind that sorting is *always* performed when scandir() is called. String sorting takes O(|s|n log n) runtime, and this adds to the burden of the server's memory and processing power.

Therefore, whenever the alphabetical order of the directory content is unimportant, especially if sorting is to be performed by another order, or the natural order of the files on the filesystem is to be utilized, the use of opendir(), readdir() and closedir() combined is always preferred to scandir().

Saw banzai monkeys code and tweaked it a little. I don't have scandir. So I had to play with the suggested use for php4.Pretty new to PHP so beer with me. This will show your current directory as a link called "Back" and will list all of your files in a menu. I wanted this because I have a lot of static pages and needed a menu that would auto update every time I added a file.

/*this first section above will get your current folder or directory and since I have a "-" between the words of my file I have to strip them to look good if I want to show the current folder or directory in the title of the first link*/$dir = '.';$dh = opendir($dir);while (false !== ($filename = readdir($dh))) {$files[] =$filename;}$t=array_slice($files,2);$f=array_search('index.php',$t);/*this code above with the variable $t gets rid of the '.' and the '..' parent and ancestor files. And the variable $f finds the index file and with the code below 'unset' let you use $f as the key to get rid of that file.*/unset($t[$f]); print('<ul align="left">'); print('<li><a href="." title="'.$directoryuppercasewords.'">Back</a></br></li>'); foreach($t as $key => $value){$phpkill=str_replace('.php', '', $value);$htmlkill=str_replace('.html', '', $phpkill);$dashkill=str_replace('-',' ',$htmlkill);$uppercasewords=ucwords($dashkill);

print('<li><a href="' . $dir . '/' . $value . '" title="'.$uppercasewords.'>' . $uppercasewords . "</a></br></li>"); } print('</ul>');closedir($dh);?>I basically made all the variables so they could explain themselves, Regular expression is not my strong point right now, just becoming familiar with php functions is more of a priority, I hope this is usefull to someone.

<?phpfunction pathFilter ($path, $aFilter) {// returns true iff $path survives the tests from $aFilter // $aFilter is an array of regular expressions: [-]/regExp/modifiers // if there is a leading '-' it means exclude $path upon a match (a NOT test) // If the first expression has a leading '-', $path is in, unless it gets excluded. // Otherwise, $path is out, unless it gets included via the filter tests. // The tests are applied in succession. // A NOT test is applied only if $path is currently (within the tests) included // Other tests are applied only if $path is currently excluded. Thus, // array("/a/", "-/b/", "/c/") => passes if $path has a c or if $path has an a but no b // array("/a/", "/c/", "-/b/") => passes if $path has an a or c, but no b // array("-/b/", "/a/", "/c/") => passes if $path has no b, or if $path has an a or cif (!$aFilter) return true; // automatic inclusion (pass) if no filtersforeach ($aFilter as $filter) break; // we don't know how it's indexed$in = $filter[0]=="-"; // initial in/exclusion based on first filterforeach ($aFilter as $filter) // walk the filtersif ($in==$not=($filter[0]=="-")) // testing only when necessary$in ^= preg_match(substr($filter,$not),$path); // flip in/exclusion upon a matchreturn $in;}?>

If you would like to use scandir on the root directory of your server, you would imagine the command to be either scandir("") or scandir("/"), but neither work. However, scandir(".") works perfectly. Use scandir("/") and scandir("..") to poke around the Linuxy areas of your webhost. At least, these are the observations I've made with my own webhost when it comes to root directory scandir.