Editing a PHP File, with another php file, using Fwrite

Ron picture Ron · Jun 21, 2012 · Viewed 13.8k times · Source

My last question wasn't explained very well.

What I'm trying to do here is insert data into a PHP File, Using the fwrite feature on another .php file.

To keep this simple, I'm labelling the one I want data inserted as file.php and the one I'm using fwrite to execute on, is edit.php

Now, I got the writing thing down, what my problem is, is I need to INSERT that data, Before the closing php tag on file.php.

What I tried doing was, deleting the closing php tag, writing the data, and then rewriting the tag.

Here is my source code for that:

<?php
$rows = file("file.php");    
$tagremove = "?>";
foreach($rows as $key => $row) {
if(preg_match("/($tagremove)/", $row)) {
    unset($rows[$key]);
}
}
file_put_contents("file.php", implode("", $rows));

$User = $_GET["user"];
$File = "file.php"; 
$Handle = fopen($File, "a");
fwrite($Handle, "");
fwrite($Handle, $User);
fwrite($Handle, "\r\n");
fwrite($Handle, "?>");
print "Data Written"; 
fclose($Handle); 
?>

When I run this on Edit.php, it inserts that data into the file, but its only writing to the first line, and replacing whatever is already there. (In my case its the opening php tag). I don't know what I'm doing wrong, or if there is another way to do this, but any assistance would be appreciated.

Edit: this is again for a chat client.

I'm having a file, that sends a message into a .txt file that the client then reads.

And that file is reading file.php (staff.php) to check if the user submitting is a staff member.

If it comes up true that the user is a staff member, then it changes the username variable in the send.php.

And so far, the send.php has only sucessfully, included the Staff.php, I've tried staff.txt, and the reason is, php code is in the staff.php.

Answer

Dador picture Dador · Jun 21, 2012

Try this:

$data="echo 'hello world!';";
$filecontent=file_get_contents('file.php');
// position of "?>"
$pos=strpos($filecontent, '?>');
$filecontent=substr($filecontent, 0, $pos)."\r\n".$data."\r\n".substr($filecontent, $pos);
file_put_contents("file.php", $filecontent);

Please don't forget, that you need to check data from user.