0

Need to find a simple solution to the following:

I have a php file that, when executed, should be able to replace a specific line of code within itself, with a different value on that line.

I came up with this so far:

$file = "file.php";
$content = file($file); 
foreach($content as $lineNumber => &$lineContent) {
    if($lineNumber == 19) {

        $lineContent .= "replacement_string";
    }
}

$allContent = implode("", $content);
file_put_contents($file, $allContent);

However, that does not replace the specific line. It adds the new string on a new line and that's it. I need that specific line ERASED and then REPLACED with the new string, on that line.

How would I continue about doing that? I'd love some pointers.

user3942918
  • 25,539
  • 11
  • 55
  • 67
lakumba
  • 19
  • 1
  • 5
  • 1
    Why would you want to do that? Store your data in a database or even a text-file but don't modify the script you are executing. Or any other script. – jeroen Mar 21 '15 at 12:56
  • This sounds line the foundation for a _huge_ security issue... – arkascha Mar 21 '15 at 12:59
  • Also this approach won't scale. It will only work for reasonable small files. Because you keep the whole file in memory, actually 2 times at a time. – arkascha Mar 21 '15 at 13:00
  • 19th line after `file()` usage? why not try change 18th index – Kevin Mar 21 '15 at 13:08

2 Answers2

2

Since file() creates an array, make use of the index to select the line. Don't forget that array indexes start at 0!

$file = "file.php";
$content = file($file); 

$content[19] = "replacement_string\r\n";

$allContent = implode("", $content);
file_put_contents($file, $allContent);
andreini
  • 188
  • 1
  • 3
  • 17
0

Your problem is the .= in the $lineContent .= "replacement_string"; line. Just use = or use the str_replace() or str_ireplace() function.

redelschaap
  • 2,774
  • 2
  • 19
  • 32