The following function performs generic recursive directory tree traversal. Examples of how to use it follow the code:
function traverseDirTree($base,$fileFunc,$dirFunc=null,$afterDirFunc=null){
$subdirectories=opendir($base);
while (($subdirectory=readdir($subdirectories))!==false){
$path=$base.$subdirectory;
if (is_file($path)){
if ($fileFunc!==null) $fileFunc($path);
}else{
if ($dirFunc!==null) $dirFunc($path);
if (($subdirectory!='.') && ($subdirectory!='..')){
traverseDirTree($path.'/',$fileFunc,$dirFunc,$afterDirFunc);
}
if ($afterDirFunc!==null) $afterDirFunc($path);
}
}
}
Basic usage
The $base parameter is the directory in which to start the traversal — this must end with a stroke (/).
The $fileFunc, $dirFunc and $afterDirFunc defines the names of functions to execute on files, on directories before recursing, and on directories after recursing.
These may be null, an trailing nulls can be omitted — traverseDirTree('/','processDir',null,null) is equivalent to traverseDirTree('/','processDir').
The functions should take one parameter — the full path to the file or directory (excluding the trailing stroke in directories).
Example
The following example illustrates how to use the function to produce a directory listing, defining the $fileFunc and $dirFunc parameters. It extracts the file or directory name from the path, and indents it appropriately.
function outputPath($path){
$level=substr_count($path,'/');
for ($i=1;$i<$level;$i++) echo ' ';
echo basename($path);
echo "\n";
}
echo '<pre>';
traverseDirTree('/','outputpath','outputpath');
echo '</pre>';
The $afterDirFunc parameter would rarely be used. An example of when it would be appropriate would be in code that converted spaces in directory names to underscores. In this case the renaming must take place after recursing, otherwise the directory being recursed into would no longer exist.