Talk:Work:error log Reader
Contents |
1. New filelist() Function
The one advantage of this function is it can be used in other scripts.
function filelist($base,$fileFunc,$dirFunc=null,$afterDirFunc=null){ $sub=opendir($base); while (($sub=readdir($sub))!==false){ $path=$base.$sub; if (is_file($path)){ if ($fileFunc!==null) $fileFunc($path); }else{ if ($dirFunc!==null) $dirFunc($path); if (($sub!='.') && ($sub!='..')){ filelist($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 — filelist('/','processDir',null,null) is equivalent to filelist('/','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 '<a href="$_SERVER['PHP_SELF']?file=base64_encode($path)" title="basename($path)">$path</a>'; echo "<br />\n"; } echo '<pre>'; filelist('/','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.
2. Using the Find method
function filelist($q) { $home = getHome(); $a = `find $home -name $q`; foreach ($a as $result) { echo "<a href='$_SERVER['PHP_SELF']?file=base64_encode($q)' title='$q'>"; } } function getHome(){ $home_array = $_SERVER['SCRIPT_FILENAME']; $home_split = split ('/', $home_array); $home = "/".$home_split['1']."/".$home_split['2']; return $home; }
This example is basic, and requires access to the find command.... but it may be lighter on resources, the current version is slow, I'm not sure Example 1 would be much better, we'll need to benchmark it.
3. Use scandir();
Some research suggests http://us3.php.net/manual/en/function.scandir.php would be faster.