0

I am trying to make a simple diary website where I enter in my text into the text area i then push submit and it will display on my current screen. I then want to be able to enter more text into my text area and when i push submit it just shows it to me on a new line. When I submit the 3 strings test, test1, and test2 I get the following.

Yes the test still works This is a test the test was successful This is a test

I want this output

This is a test
the test was successful
Yes the test still works

here is my php

<?php
$msg = $_POST["msg"];
$posts = file_get_contents("posts.txt");
chmod("posts.txt", 0777);
$posts = "$msg\r\n" . $posts;
file_put_contents("posts.txt", $posts, FILE_APPEND);
echo $posts;
?>
craft3maker
  • 117
  • 1
  • 4
  • 9

1 Answers1

0

Try adding echo nl2br($posts); instead. HTML does not recognize the newline character.

Recommend removing the last \r\n from the file or do the following to get rid of the rogue line at the bottom:

// take off the last two characters
$posts = substr($posts, 0, -2));

// convert the newlines
$posts = nl2br($posts);

// output
echo $posts;

To fix the erroneous posts problem:

// get the message
$msg = $_POST["msg"];

// store the original posts from the file
$original_posts = file_get_contents("posts.txt");

// set permissions (this isn't really required)
chmod("posts.txt", 0777);

// prepend the message to the whole file of posts
$posts = "$msg\r\n" . $original_posts;

// output everything
echo nl2br($posts);

// write the entire file (no prepend) to the text file
file_put_contents("posts.txt", $posts);
brian
  • 2,745
  • 2
  • 17
  • 33
  • ok that helped me seperate it into new lines I am just having an issue now with the output. When I enter my third item i get 4 outputs in the following format: i like to test This is a test the test was successful This is a test – craft3maker Dec 06 '13 at 00:23
  • 4 output? As in, 4 lines of output? It's most likely because of the last \r\n. I'll update the answer. – brian Dec 06 '13 at 00:25
  • when i look at my file it seems to be adding a new output. so if i enter 1,2,3 as different inputs i get 1,2,1,3 as output i think it has to do with how i am writing my data to a file but i am not sure. – craft3maker Dec 06 '13 at 00:30
  • Another issue is you are appending the new post along with the posts from the file onto the end of the entire file. – brian Dec 06 '13 at 00:32
  • yea i did that because i want to print the whole file of posts.txt and when i didnt have that in there i was just get the last line i inputed as an output so i added the FILE_APPEND to fix it and it prints the whole file just not what I want lol. – craft3maker Dec 06 '13 at 00:37
  • You're welcome :). Unfortunately, file_put_contents doesn't have a FILE_PREPEND flag. You must write everything to the file if you've added something to the beginning. – brian Dec 06 '13 at 00:46