PHP - Optimizing Recursive Method 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,&amp;$results_array,$depth)
{
    global $search_string;
    global $dir_count;
    global $file_count;
    global $working_url;
    global $max_depth;

    if($max_depth&gt;=($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'=&gt;$file,'path'=&gt;$working_dir,'url'=&gt;$working_url.str_replace($_SERVER["DOCUMENT_ROOT"],'',$working_dir));

            $file_count++;
        }
    }

    return;
}
I answered this moments ago, but same applies

https://stackoverflow.com/questions/8108175/php-usleep-to-prevent-script-timeout/8108229#8108229

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 ;)