Here are two versions of the same function to list all files in a directory tree.
The first one is recursive (calls itself while going through subdirectories) :
<?php
function rec_listFiles( $from = '.')
{
if(! is_dir($from))
return false;
$files = array();
if( $dh = opendir($from))
{
while( false !== ($file = readdir($dh)))
{
if( $file == '.' || $file == '..')
continue;
$path = $from . '/' . $file;
if( is_dir($path) )
$files += rec_listFiles($path);
else
$files[] = $path;
}
closedir($dh);
}
return $files;
}
?>
The second one is iterative (uses less memory) :
<?php
function listFiles( $from = '.')
{
if(! is_dir($from))
return false;
$files = array();
$dirs = array( $from);
while( NULL !== ($dir = array_pop( $dirs)))
{
if( $dh = opendir($dir))
{
while( false !== ($file = readdir($dh)))
{
if( $file == '.' || $file == '..')
continue;
$path = $dir . '/' . $file;
if( is_dir($path))
$dirs[] = $path;
else
$files[] = $path;
}
closedir($dh);
}
}
return $files;
}
?>
The iterative version should be a little faster most of the time, but the big difference is in the memory usage.
Here is also a profiling function (works in php5 only) :
<?php
function profile( $func, $trydir)
{
$mem1 = memory_get_usage();
echo '<pre>-----------------------
Test run for '.$func.'() ...
'; flush();
$time_start = microtime(true);
$list = $func( $trydir);
$time = microtime(true) - $time_start;
echo 'Finished : '.count($list).' files</pre>';
$mem2 = memory_get_peak_usage();
printf( '<pre>Max memory for '.$func.'() : %0.2f kbytes
Running time for '.$func.'() : %0.f s</pre>',
($mem2-$mem1)/1024.0, $time);
return $list;
}
?>