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

血红的双手。 提交于 2019-12-03 06:25:19

问题


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.


回答1:


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.




回答2:


Ok much better alternative use a data file. Ill use json because its easy to use an very easy to parse by human eyes as well:

// read file
$data = file_get_contents('data.json');
$json = json_decode($data, true);

// manipulate data
$json['users'][] = $_GET['user'];

// write out file
$dataNew = json_encode($json);
file_put_contents('data.json', $dataNew);

the reason is, php code is in the staff.php

Well this isnt something you workaround. You should be writing/reading this kind of information form a data stor - that could be a file or a database... but not an actual script.



来源:https://stackoverflow.com/questions/11146626/editing-a-php-file-with-another-php-file-using-fwrite

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!