Question: Lets say I have `Text` that is a POST textarea. In that field I should be able to put whatever I'd like to write. Such as XSS, SQL, and other eventual bad codes. For the markup I'll use the BBCode, so I'd like to display the code without making it work.   

The thing, of course, that I wanna avoid, is that the DB gets screwed! Is there an **extremely safe** way to do this?

The steps I actually do are:

1. Specify the Content-Type and Charset `Content-Type: text/html; charset=UTF-8`
2. Limit the input. `Ex.: Max 500 characters`
3. Use htmlentities() `$GoodText = htmlentities($Text, ENT_QUOTES, "UTF-8");`
4. Use mysql\_real\_escape\_string() `$GoodText = mysql_real_escape_string($GoodText);`
5. Store it in the DB `$db->store($User, $GoodText);`

As far as I read the step 3 and 4 are quite the same, but I'd like to get an explanation.   

Anyway, is this a working method?   

Should I also use tokens for POST forms?

Answer: 
Quick overview for you:

* Use tokens against cross site request
forgeries.
* Use htmlspecialchars/entities against
cross site scripting attacks.
* Use mysql\_real\_escape\_string against
SQL injection.

For database security, you'll only have to escape using the mysql\_real\_escape\_string function.
I use this function that is basically steps 3 and 4 combined. It works with one dimensional array and strings.

```
function escape($mixed){
    if(is_array($mixed)){
        foreach($mixed as $m => $value){
            $mixed[$m] = mysql_real_escape_string(htmlspecialchars($value, ENT_QUOTES, "UTF-8"));
        }
    }else{
        $mixed =  mysql_real_escape_string(htmlspecialchars($mixed, ENT_QUOTES, "UTF-8"));
    }
return $mixed;
}

```