Looking For PHP Script To Recursively Search & Replace Server Files

hm25819

Newbie
Joined
Mar 24, 2014
Messages
21
Reaction score
0
I do not want to reinvent the wheel.

I need a PHP script that will search and replace server files recursively.

This need not be something you've written. I would be happy with a link. Can anyone help with this type of script? There are a number of php files on my server, each of which have one line of code that I would like to replace with a different line of code. However, within the code there are some characters which need to be escaped in the php code in order to replace them, so some php code I have found online cannot work with this particular piece of code for that reason. This can be code or a program/utility that would run on an apache linux/ php server. Any help would be appreciated. Thank you.
 
there are log of ways to do it...
please be more specific..
how you search the files, by name? by content.
what you replace? the file? content in the file?
 
stackoverflow_com/questions/6155533/loop-code-for-each-file-in-a-directory - you get a list of files from the directory you want to edit, and do with files everything you want.
 
It can be solved in one line with shell script:
Code:
find ./myFolder -type f -exec sed -i 's/Application/whatever/g' '{}' \;

But in php you will need something like this (just sample, test it before use):

PHP:
<?php

replaceRec ("DIR_WITH_FILES", "FROM", "TO");

function replaceRec ($dn, $from, $to){
  $dh = opendir ($dn);
  while ($fn=readdir($dh)) {
    if ($fn != "." && $fn != "..") {
      $ffn = $dn . "/" . $fn;
      if (is_dir ($ffn)) {
         replaceRec ($ffn, $from, $to);
      } else {
         $c = file_get_contents ($ffn);
         $c2 = str_replace ($from, $to, $c);
         if ($c2 != $c) {
           file_put_contents ($ffn, $c2);
         }
      }
    }
  }
}
?>
 
Back
Top