Search code examples
phpdynamiclinefopenupdates

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


Solution

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

    more simple:

    $a="<?php\r\necho 'whatev';\r\n".substr($a,7);