简体   繁体   中英

Encode '\r\n' in HTML text input

The below PHP code prints a string taken from an HTML text input.

<div class="form-group">
<label for="sender">Your text</label>
<input type="text" name="sender" id="sender" class="form-control" placeholder="example" />
</div>

<?php
print $_POST["sender"]." \r\nSecond senetence.";
?>

Please note the second \\r\\n in the concatenated string.

HTML form

When I enter: \\r\\nFirst sentence. in the HTML text input, the output is:

\r\nFirst sentence. Second sentence.

Why is the first \\r\\n taken literally and how can I resolve this?

I've tried '\\r\\n' "\\r\\n" \\\\r\\\\n but non seem to work. Also since I want the \\r\\n in the PHP string, <br />, &#13 and &#10 won't work.

<input type="*"> doesn't accept newlines.

Use <textarea rows="1"></textarea> instead.

Bear in mind that you will have to show your output in a <pre> or another <textarea> if you want to show the newlines. Other possibility is using PHP's nl2br() .

If you cannot change the code, it is more complicated but still possible.

The browser is going to filter/encode/sanitize everything you enter in the text field, so you will have to do something after that step.

My suggestion is:

  • use Firefox
  • install extension TamperData
  • use it to modify the text you send, eg inserting %0D%0A at the beginning; which is the URL-encoded version of \\r\\n

A little bit cumbersome but doable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM