Secure PHP: Sanitize form input to protect against XSS
I did another post aimed at web surfers, helping people to protect themselves against xss already embedded in websites. Now I just want to quickly point out something to PHP coders, something that my travels around the web reveal is missing in a shocking number of sites: Basic security against this kind of attack being executed through form submissions in your website.
It's so simple. If you're coding your site in PHP (and why would you use anything else, really? ;)), make sure to sanitize form input by using either the strip_tags() or htmlentities() functions!
So...
$comments = htmlentities($_POST['comments']);
print $comments;
or
$comments = strip_tags($_POST['comments']);
print $comments;
(emphasis on functions added)
NOT the same code without those handy functions!
The difference between strip_tags() and htmlentities() is that strip_tags() eliminates script tags entirely while htmlentities() transforms them into html entities like "<" (instead of "<") or "©" (instead of "©") disallowing dangerous coding symbols. The html_entities function is a little more useful for forensics as you can track exactly what the attacker is trying to do, but strip_tags works if you just want to foil them.
Either way, it's a small security measure that you should not miss, and a shocking number of professional coders do miss it.


Post new comment