I have a function that is supposed to make text entered in a form safe before it gets posted in a database - is it good enough? does it cover all the security possibilities? Is there a better way of doing the same? Thanks! function cleanText($textstring, $stringLength) { $cleanString = nl2br($textstring); $cleanString = strip_tags($cleanString,"<b><p><br>"); $cleanString = trim ($cleanString); $cleanString = mysql_real_escape_string($cleanString); if(strlen($cleanString)>$stringlength) $cleanString=substr($cleanString,0,$stringLength); return $cleanString; } Code (markup):
mysql_real_escape_string is supposed to be the last thing you do. Yet you do it before you do the possible substr. So that could introduce a vulnerability (or at least incorrect SQL generation) Also, you're doing strip tags but allowing <p> etc.. This means you probably aren't doing htmlspecialchars on the output page? Again vulnerable since people could write <p onhover="javascript:..">etc</p> You should probably use something like htmlpurifier.org instead. Or if that's overkill, some regexes could do the trick as well.