SULTAN SULTAN - 2 months ago 5x
HTML Question

User inputs, clean and sanitize before sending to db

I've searched a lot of the questions here and I found that they either very old or suggesting using prepared statements PDO which I am not using. So I need your help please.

I have a small discussion/chat box where a user submit a message using a


What I need is sanitize and filter the user input so it only accepts plain texts (e.g. no tags, no html tags, no scripts no links, etc). Also, it is important to allow line breaks.

Based on my reading I am doing the following in the following order:

  1. trim()

  2. htmlentities($comment, ENT_NOQUOTES)

  3. mysqli_real_escape_string()

  4. nl2br()

Is what I am doing is right? or I am missing something?

Also is there anything I have to do when
ing the data from the db?

really, appreciate your help and kindness


First, keep the text logical and clean:

trim() -- OK
htmlentities($comment, ENT_NOQUOTES)  -- No; do later
mysqli_real_escape_string()  -- Yes; required by API
nl2br()  -- No; see below

The logic behind those recommendations: The data in the database should be just plain data. Not htmlentities, not br-tags. But, you must do the escape_string in order to pass data from PHP to MySQL; the escapes will not be stored.

But... That is only the middle step. Where did the data come from? Older versions of PHP try to "protect" you be adding escapes and other junk that works OK for HTML, but screws up MySQL. Turn off such magic escaping, and get the raw data.

Where does the data go to? Probably HTML? After SELECTing the data back out of the table, then first do htmlentities() and (optionally) nl2br();

Note, if you are expecting to preserve things like <I> (for italic), you are asking for trouble -- big trouble. All a hacker needs to do is <script> ... to inject all sorts of nastiness into your web page and possibly your entire system.