Search and replace code in all files of a directory by using php

php

Posted on 18 Sep 15 by Vickey
  536



In a editor normally we use find and replace operation. If i want to change a variable name in my file i use find and replace option and replace it by new variable name at each place. The same thing we can use for more then one files by using php script. If you want to replace a big part of a code you can use this method. For example once because of some virus insfection there was a big part of a code added in my all files and it was very difficult to remove this from each files so i created a script for this.
First i created a text file 'code.txt' and copy paste the code in this file which i want to remove from my all files.

$dir =  "/var/www/html/code.txt";

I stored this file at my web root directory and create a new file name as 'replace_code.php' and write the below script in this file

$path_to_string     =   "/var/www/html/code.txt";  // add unwanted code here

$dir =  "/var/www/html/myprojects/libraries/"; // here are my all files from which i want to remove unwanted code

$string             =   file_get_contents($path_to_string);

if (is_dir($dir)){
    
    if ($dh = opendir($dir)){
        while (($file = readdir($dh)) !== false){
           $ext = pathinfo($file, PATHINFO_EXTENSION);
            if($ext=='php'){
                $path_to_file = $dir.$file;
                if(file_exists($path_to_file)){
                $file_contents = file_get_contents($path_to_file);
                $file_contents = str_replace($string,"",$file_contents);
                file_put_contents($path_to_file,$file_contents);
                echo "File Path==>" . $path_to_file; echo "
";
               
                }
            }
        }
        closedir($dh);
    }
}
else{
    echo "There is no directory with this name". $dir;
}

and by running this script i finally removed all unwanted code from my all files. Please let me know if you have any question or comments on this script


If this post help you reduce time to develop, you can help me to maintain this website :)
www.000webhost.com