Question

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;
?>
Was it helpful?

Solution

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);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top