paksyh15 paksyh15 - 3 months ago 9
PHP Question

PHP writing variables and string to text file

I'm trying to write to file like this:

<?php
date_default_timezone_set('Europe/Budapest');

if(isset($_POST['user'])) {
global $user;
$user = $_POST['user'];
} else {
die("Nincs user beállítva!");
}
if(isset($_POST['pass'])) {
global $pass;
$pass = $_POST['pass'];
} else {
die("Nincs pass beállítva!");
}

if(!isset($_POST['msg'])) {
die("Nincs üzenet!");
} else {
global $msg;
$msg = $_POST['msg'];
}

if(!file_exists("logfile.txt")) {
die("Nem létezik a logfile.txt!");
}
$cont = file_get_contents("logfile.txt");
file_put_contents("logfile.txt","{$user}: {$msg}\n{$cont}"); //<-- Tried this one so many ways
?>


And it gives me this in the txt file:

<? global $user; echo $user; ?>: test


No matter what i change in the
file_put_contents
, it always give something similar to this.
Thanks for the help in advance.

EDIT: I made the edit that @Barmar suggested, but it is still doing the same thing:

<form name="send" action="chat_send.php" method="post">
<input type="text" name="msg" autocomplete="off" value="">
<?php
global $user;
echo '<input type="hidden" name="user" value="' . $user . '">';
...
</form>

Answer

There's nothing wrong with how you're writing to the file. The problem is most likely with how you're setting $_POST['user']. It looks to me like the script that created the form did something like:

echo '<input type="hidden" name="user" value="<?php global $user; echo $user; ?>">';

You can't use <?php ... ?> in the middle of a string to execute PHP code; That's used when you're outputing normal HTML after ?>, to get back into PHP execution mode temporarily. So your form just contains the literal string ?php global $user; echo $user; ?> in the hidden input value.

In a string, you use concatenation, so it should be:

global $user;
echo '<input type="hidden" name="user" value="' . $user . '">';

Or you can return to HTML mode first:

?>
<form name="send" action="chat_send.php" method="post">
    <input type="text" name="msg" autocomplete="off" value="">
    <input type="hidden" name="user" value="<?php global $user; echo $user; ?>">
    ...
</form>
<?php
Comments