Log in

View Full Version : Resolved php form to text append



kinshiro
04-26-2009, 06:44 PM
I am new to this forum and new to PHP. But, I'm looking for help with a piece of code I have been working on. What I'm trying to do is use a form to post to a textfile and each time someone uses the form, have the text be appended. I started out with a simple form design to see if I could get it to work and then I plan on doing something more complex with it, but I can't seem to get the simple one to work right.
My form code:

<form action="addition.php" method="post">

<input type="text" name="addition"> <br>
<input type="submit" value="submit">
</form>

My php (addition.php):


$fn = "file.txt";
$file = fopen($fn, "a+");
$size = filesize($fn);
$space.= "\n";
if($_POST['addition']) fwrite($file, $_POST['addition']);

$text = fread($file, $size);
fwrite ($file, $space);
fwrite ($file, "____");
fclose($file);


My problem is that I can't figure out how to have the next post, input a carriage return so that the new data starts on a new line, or even to input some text before the user's input. Any help would be appreciated.

borris83
04-27-2009, 09:30 AM
Replace the line
$space.= "\n";

with
$space.= chr(13) . chr(10);

It will work.. I tested with your code.

Schmoopy
04-27-2009, 09:48 AM
Alternatively you can write the space like this:



$space = "\r\n";


And then I've added some validation, this also shows the output of the text file after the fwrite:



if($_POST['addition']) {
$fn = "file.txt";
$file = fopen($fn, "a+");
$space = "<br />\r\n";
fwrite($file, $_POST['addition']);
fwrite ($file, $space);
fclose($file);
// Open file again to read new content
$reader = fopen($fn, "r");
$size = filesize($fn);
$data = fread($reader, $size);
echo "Your message has been added.<br />\n";
echo $data;
}
else
echo 'You didn\'t enter any text.';

kinshiro
04-27-2009, 12:25 PM
Thanks guys. I appreciate it. :)