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:
Specify the Content-Type and Charset Content-Type: text/html; charset=UTF-8
Limit the input. Ex.: Max 500 characters
Use htmlentities() $GoodText = htmlentities($Text, ENT_QUOTES, "UTF-8");
Use mysql_real_escape_string() $GoodText = mysql_real_escape_string($GoodText);
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?
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;
}