I'm V I'm V - 4 months ago 9
PHP Question

PHP- \n does not work

when i try

echo "anything \n whatever";

the result :



But when i try it from user input it doesn't work


<h1>Authentication v 0.04</h1>
<form action="" method="GET">
<input type="text" name="username" /><br/><br/>
<input type="submit" value="connect" /><br/><br/>
<fieldset><legend>Authentication log</legend><pre>

ini_set('display_errors', 1);
echo $_GET['username'];


$_GET['username'] = "anything \n whatever"

the result is

"anything \n whatever"

it treats
as string !!!

why ?


\n is an escape sequence which represents an end of line [1]. An escape sequence only makes sense on PHP interpolation (i.e. double quotes).

In HTML \n has no special meaning so it is printed as a string. [2]

If there is an actual new line, you may want to use the nl2br function (http://php.net/manual/en/function.nl2br.php) to automatically convert any \n to a <br> tag.

If you want to convert any literal \n to <br>, you may want to use a str_replace function (http://php.net/manual/en/function.str-replace.php) for example like this:

echo str_replace ('\n', '<br>', $_GET['username']);

Notice the single quotes to avoid further interpolation.

[1] In fact, it is a new line only on *nix systems, while it's different on Microsoft and old Mac OSx. You may want to take a look at PHP_EOLconstant (http://php.net/manual/en/reserved.constants.php).

[2] In fact, it is printed as a new line in the HTML source, which is a text file.