0

I am trying to get a simple form which will write to a file using php. But I am running into an error where whenever I try and write a value got through post, it writes '0' to the file instead of the value.

I have a form like the following:

<form method="post" action="test.php">
<input type="text" name="user" />
<input type="submit" value="submit"/>
</form>

And test.php gets the user from the form via:

$user = $_POST['user'];

I can display $user on the page fine, and I have been able to write strings to the file using fwrite fine as well. But whenever I fwrite($file,$user) the only thing written is a 0. What am I doing wrong?

ztnewman
  • 11
  • 1
  • 4

2 Answers2

3

Are you missing the file handle,not the file, in fwrite

$user = $_POST['user'];
$fh = fopen("file.txt","a");
fwrite($fh,($user."\r\n")); // add newline for next time
fclose($fh);
ComFreek
  • 29,044
  • 18
  • 104
  • 156
Samuel Cook
  • 16,620
  • 7
  • 50
  • 62
0

You can also simply use file_put_contents with FILE_APPEND flag:

<?php 
if($_SERVER['REQUEST_METHOD']=='POST'){
    if(!empty($_POST['user'])){
        file_put_contents('file.txt',trim($_POST['user'])."\n",FILE_APPEND);
    }
}
?>
Lawrence Cherone
  • 46,049
  • 7
  • 62
  • 106