Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

Here is a recursive function that I wrote to search a file-system to a child depth defined by $depth.

Could it be optimized more?

function stringSearch($working_dir,&$results_array,$depth)
{
    global $search_string;
    global $dir_count;
    global $file_count;
    global $working_url;
    global $max_depth;

    if($max_depth>=($depth+1))
    {
        $dir_array = glob($working_dir.'/*', GLOB_ONLYDIR);
        foreach($dir_array as $new_path)
        {
            stringSearch($new_path,$results_array,($depth+1));
            $dir_count++;
        }
    }

    $handle = opendir($working_dir);
    while ($file = readdir($handle)) 
    {
        if(is_file($working_dir.'/'.$file))
        {
            if(stripos(str_replace('_',' ',$file),$search_string))
                $results_array[] = array('file'=>$file,'path'=>$working_dir,'url'=>$working_url.str_replace($_SERVER["DOCUMENT_ROOT"],'',$working_dir));

            $file_count++;
        }
    }

    return;
}
share|improve this question

migrated from stackoverflow.com Nov 13 '11 at 15:03

This question came from our site for professional and enthusiast programmers.

2  
Should look into DirectoryIterator (us2.php.net/directoryiterator), may help clean up your code a bit. –  Digital Precision Nov 12 '11 at 19:17
    
Hmm. . . I'd call out to find -name '*' -maxdepth 3 . . . :) (Syntax might not quite be correct, I'm currently on a windows machine, assumed Linux) –  Levi Morrison Nov 12 '11 at 19:20
    
Thanks, I'll check it out. I also found that making $results_array global rather than passing by reference greatly improved performance. –  cbm3384 Nov 12 '11 at 19:21
6  
also have a look at RecursiveDirectoryIterator, RecursiveIteratorIterator, RegexIterator, GlobIterator and FilterIterator. Or just look at all the iterators. In any case, you dont want that piece of code of yours. –  Gordon Nov 12 '11 at 19:35

2 Answers 2

$it1 = new RecursiveDirectoryIterator($working_dir);
$it2 = new RecursiveIteratorIterator($it1);
$it2->setMaxDepth($depth);

foreach ($it2 as $path => $file)
{
   // do something
}
share|improve this answer

I answered this moments ago, but same applies

PHP usleep to prevent script timeout

If you simply use : $handle = opendir($working_dir); you can find yourself waiting for the script to timeout on non existing directories. So atleast use:

if (! $handle = opendir($working_dir)) 
  exit(0);

Its generally way faster to just check if functions are even possible before you start them, although it might feel like your implementing way to many if statements, but if statements are fast and most errors are not ;)

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.