Skip to content
Advertisement

Edit PHP file using another PHP file and add a line on top of it

I have a PHP file that I want to dynamically add lines to it whenever I want.

Let’s say I have foo.php which has these inside it:

<?php

echo "foo!";

?>

but I want to be able to add a line I specify in another file as a variable to be added on top of it and save the old content as well, to be like this:

<?php

echo "bar!";

echo "foo!";

?>

whenever I run my other file that adds the top line, I want it to add this line no matter what:

echo "bar!";

so if I run it twice the file would be like this:

<?php

echo "bar!";

echo "bar!";

echo "foo!";

?>

I know about the security issues and the file will be protected, I just don’t know what’s the best way to do this, fopen? curl? please help me find out the best way to do this. Thanks

Advertisement

Answer

$a = explode("rn", file_get_contents('file')); 
array_splice($a, 1, 0, array('echo 'whatever';'));
$a = implode("rn", $a);
file_put_contents('file', $a);

more simple:

$a="<?phprnecho 'whatev';rn".substr($a,7);
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement