Preserve and display text exactly how it is typed

2019-01-12 12:28发布

问题:

I'm having lots of trouble preserving the exact look of how a user types out a short paragraph.

My problem is that random slashes and html show up. When people would hit enter while typing the message, "\r\n\" would show up when it's echoed later. I tried fixing that but now when the user types an apostrophe while composing a message, it gets inserted into the database with 3 back slashes, and thus echoed later with 3 back slashes with the apostrophe. Frustrating! I want to just start over!

Here's what I do.

  1. User types a message in an input field and hits submit.
  2. That message gets inserted into the database with type varchar(280) via php.
  3. That message gets echoed via php.

I've tried many different things like nlbr and strip_tags and stripslashes and mysql_real_escape_string and others. I might be using these all in a certain combination that messes it up.

So my question is what is the best way to preserve exactly how someone composes a text paragraph to be later echoed via php to look just like how they typed it?

回答1:

  1. Make sure Magic Quotes are off or, if you can't disable them, cleanse your strings from them. Read the manual for details: http://www.php.net/manual/en/security.magicquotes.php
  2. When inserting your text into the database, escape it properly for SQL syntax once or, better, use prepared statements. See How can I prevent SQL injection in PHP? and The Great Escapism (Or: What You Need To Know To Work With Text Within Text).
  3. When outputting to HTML, use htmlspecialchars to avoid HTML injection or plain syntax problems and afterwards use nl2br to format line breaks specifically for HTML.

That's basically it.



回答2:

On the second step you need to escape it with mysql function.

But for correct outputing it you need to do following

<pre><?= htmlentities($mysqlRow['data']); ?></pre>

This will get from database result needed information and will outputs it like it is. With all spaces and tabs and html tags in it. (If user enters <html> this will output <html> like text)