-1

I am trying to write a function in which a string of text is written with timestamps to the file "text2.txt", I want each entry to be on a new line, but PHP_EOL does not seem to work for me.The strings simply write on the same line and does not write to a new line for each string.

Could anyone give me some pointers or ideas as to how to force the script to write to a new line every time the function is activated? Some sort of example would be highly appreciated.

Thank you in advance.

<?php
  if($_SERVER['REQUEST_METHOD'] == "POST" and isset($_POST['sendmsg']))
  {
    writemsg();
  }

  function writemsg()
  {
    $txt = $_POST['tbox'];
    $file = 'text2.txt';
    $str = date("Y/m/d H:i:s",time()) . ":" . $txt;
    file_put_contents($file, $str . PHP_EOL , FILE_APPEND );
    header("Refresh:0");
  }
?>

Also, I want to get rid of the character count on the end of the string when using the below code :

<?php
  echo readfile("text2.txt");
?>

Is there any way for the character count to be disabled or another way to read the text file so it does not show the character count?

Cell
  • 53
  • 5

2 Answers2

3

Could anyone give me some pointers or ideas as to how to force the script to write to a new line every time the function is activated? Some sort of example would be highly appreciated.

Given the code you posted I'm pretty sure newlines are properly appended to the text lines you are writing to the file.

Try opening the file text2.txt on a text editor to have a definitive confirmation.

Note that if you insert text2.txt as part of a HTML document newlines won't cause a line break in the rendered HTML by the browser.

You have to turn them into line break tags <br/>.

In order to do that simply

<?php
    echo nl2br( file_get_contents( "text2.txt" ) );
?>

Using file_get_contents will also solve your issue with the characters count display.


A note about readfile you (mis)used in the code in your answer.

Accordind to the documentation

Reads a file and writes it to the output buffer.

[...]

Returns the number of bytes read from the file. If an error occurs, FALSE is returned and unless the function was called as @readfile(), an error message is printed.

As readfile reads a file and sends the contents to the output buffer you would have:

$bytes_read = readfile( "text2.txt" );

Without the echo.

But in your case you need to operate on the contents of the file (replacing line breaks with their equivalent html tags) so using file_get_contents is more suitable.

Community
  • 1
  • 1
Paolo
  • 15,233
  • 27
  • 70
  • 91
0

To put new line in text simply put "\r\n" (must be in double quotes). Please note that if you try to read this file and output to HTML, all new line (no matter what combination) will be replaced to simple space, because new line in HTML is <br/>. Use nl2br($text) to convert new lines to <br/>'s.

For reading file use file_get_contents($file);

Justinas
  • 41,402
  • 5
  • 66
  • 96