Jump to content

Recursive FIle searching


champrock

Recommended Posts

Hi

 

I am trying to recursively search for a given file  from a directory and all the subdirectories in it. I am unable to figure out how to achieve that and output all instances of the file with the complete paths.

 

Can anyone please help me out in this? I searched php.net reference but somehow those code snippets mentioned do not return anything for me . Just a blank page. :(

 

thanks a lot for all the help.

 

 

Link to comment
Share on other sites

I have this from a while ago which was used to find a file and then replace some text in it. You could modify if for your needs:

 

<?php
function find_file($dir,$file_to_find,$text_to_find,$replacement){
    $handler = opendir($dir);
    while(false !== ($file = readdir($handler))){
        if($file != '.' && $file != '..'){
            if(is_dir($dir.'/'.$file)){//if this is a directory, recall the function with the subdirectory defined
                $sub_dir = $dir.'/'.$file;
                find_file($sub_dir,$file_to_find,$text_to_find,$replacement);	
            }else{
                if($file==$file_to_find){//this is the file we are looking for
                	echo 'found';
                	$new_contents = str_replace($text_to_find,$replacement,file_get_contents($dir.'/'.$file));	
                	$h = fopen($dir.'/'.$file,'w');
                	fwrite($h,$new_contents);
                	fclose($h);
			}
            }	
        }
    }
}
echo find_file($_SERVER['DOCUMENT_ROOT'],'test.txt','test','blah');
?>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.