Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 289
  • Last Modified:

Recursive Find/Replace text in all config files (PHP)

I want to recursively find all instances of ###foobar### and replace them with ###ZAPHU### in all files named '_config.php'

I have attached some code that does the first part-- it finds the config files.  Now I need to do the replacement.


<?php
 
$sitesDir = '/home/mydir/';
 
function my_handler($filename) {
  echo $filename . "\n<br/>";
}
 
find_files($sitesDir, '/_config.php$/', 'my_handler');
 
function find_files($path, $pattern, $callback) {
  $path = rtrim(str_replace("\\", "/", $path), '/') . '/';
  $matches = Array();
  $entries = Array();
  $dir = dir($path);
  while (false !== ($entry = $dir->read())) {
    $entries[] = $entry;
  }
  $dir->close();
  foreach ($entries as $entry) {
    $fullname = $path . $entry;
    if ($entry != '.' && $entry != '..' && is_dir($fullname)) {
      find_files($fullname, $pattern, $callback);
    } else if (is_file($fullname) && preg_match($pattern, $entry)) {
      call_user_func($callback, $fullname);
    }
  }
}
 
?>

Open in new window

0
hankknight
Asked:
hankknight
1 Solution
 
mvanrooijCommented:
If you have the full path to the file, use this function to update the file.

It takes the full path, the search string and the replace string as parameter.
function($sPathToFile,$sFind,$sReplace) {
	
	//get contents of file
	$contents = file_get_contents($sPathToFile);
	
	//replace
	$contentsNew = str_replace($sFind,$sReplace,$contents);
	
	//write back to the same file (overwrite)
	$fh = fopen($sPathToFile, 'w') or die("can't open file");
	fwrite($fh, $contentsNew);
	fclose($fh);
 
}

Open in new window

0

Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now