RSS

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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
<?php
$stringsearch = "texttosearchfor";
$dir = "./";
echo "Starting search for $stringsearch within directory $dir
";
        $listDir = array();
        if($handler = opendir($dir)) {
            while (($sub = readdir($handler)) !== FALSE) {
                if ($sub != "." &amp;&amp; $sub != ".." &amp;&amp; $sub != "Thumb.db") {
                    if(is_file($dir."/".$sub)) {
                        if(substr_count($sub,'.php'))
                            {
                            $getfilecontents = file_get_contents($dir."/".$sub);
                            if(substr_count($getfilecontents,$stringsearch)&gt;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;
    }
?>

Related posts:

  1. New Project: vBulletin-Bridge
  2. GoDaddy mod_rewrite Hell
  3. Bash, Bad Interpreter
  4. [PHP] Get current time in milliseconds
  5. [PHP] TLD List, Inc. Level 2 & 3

Your Comment