PHP Search and Replace Directory Recursively

On a message forum I regularily visit a member was having issues with code being placed in multiple files that he wanted to remove or change without having to edit each and every file manually. For this I created a search and replace function which will recursively search the directory and every file for a specific piece of code and will replace with whatever:

<!--?php
$stringsearch = "texttosearchfor";
$stringreplace = "texttoreplacewith";
$dir = "./";
SearchandReplace($dir,$stringsearch,$stringreplace);
 
function SearchandReplace($dir, $stringsearch, $stringreplace)
{
echo "Starting search for $stringsearch within directory $dir
";
        $listDir = array();
        if($handler = opendir($dir)) {
            while (($sub = readdir($handler)) !== FALSE) {
                if ($sub != "." &amp;&amp; $sub != ".." && $sub != "Thumb.db") {
                    if(is_file($dir."/".$sub)) {
                        if(substr_count($sub,'.php'))
                            {
                            $getfilecontents = file_get_contents($dir."/".$sub);
                            if(substr_count($getfilecontents,$stringsearch)>0)
                            {
                            $replacer = str_replace($stringsearch,$stringreplace,$getfilecontents);
                            // Let's make sure the file exists and is writable first.
                              if (is_writable($dir."/".$sub)) {
                                  if (!$handle = fopen($dir."/".$sub, 'w')) {
                                       echo "Cannot open file (".$dir."/".$sub.")";
                                       exit;
                                  }
                                  // Write $somecontent to our opened file.
                                  if (fwrite($handle, $replacer) === FALSE) {
                                      echo "Cannot write to file (".$dir."/".$sub.")";
                                      exit;
                                  }
                                  echo "Success, removed searched content from:"$dir."/".$sub."
";
                                  fclose($handle);
                              } else {
                                  echo "The file ".$dir."/".$sub" is not writable
";
                              }
                            }
                            }
                        $listDir[] = $sub;
                    }elseif(is_dir($dir."/".$sub)){
                        $listDir[$sub] = SearchandReplace($dir."/".$sub,$stringsearch,$stringreplace);
                    }
                }
            }
            closedir($handler);
        }
        return $listDir;
    }
}
?-->

5 thoughts on “PHP Search and Replace Directory Recursively”

  1. Your code has issues in several areas. For one, it cleans it’s self of the text your are search for. Two its lacking the variable $stringreplace value. Third, I’m not sure if it is the script or your site but someting is re-writing important characters for it to work, like greater than sign is > in your script when it should be > and the && is being replaced as well. You may want to look in to running the script your self and seeing if it works.

  2. Hi Adam,
    Thanks for your advice, you need to click “View PHP code” to view the full and formatted code. The code has been tested and does work correctly, the “& amp;”‘s are not there when you click view PHP code, let me know if you have any more problems. However I do see a problem with its recursiveness and have changed it accordingly.

  3. Very Good script !
    You have some mistakes with some “.” that fallling but after corrected that mistakes everything work fine !
    Thks very much

Leave a Reply

Your email address will not be published. Required fields are marked *