Answer the question
In order to leave comments, you need to log in
How to secure a site from a user comment with XSS, but still keep the right tags (htmlspecialchars makes the tags plain text)?
Hello. On my site, users can enter comments. These comments can contain a link (a tag with its attributes), various formatting. How do I secure the site from a user comment with XSS, but still keep the right tags (htmlspecialchars makes the tags plain text)?
Answer the question
In order to leave comments, you need to log in
HTML Purifier will help you
$config = HTMLPurifier_Config::createDefault();
$config->set('HTML.Allowed', 'p[style],span[style],em,b,strong,img[src],img[width],img[height]');
$sanitiser = new HTMLPurifier($config);
$text = $sanitiser->purify(filter_input(INPUT_POST, 'text'));
Generally speaking, strip_tags allows you to leave some tags. Actually, we leave the set of type "p", "a", "strong", "em", "br", and for greater purity, we load the dry residue as a DOMDocument, run through the nodes and clean up the attributes.
Well, or we just run through the load as a DOMDocument, run through the nodes and clean up the extra attributes, and delete the extra nodes. Preg-replace should work faster.
You can store in the database with all the html junk, and on the exhaust end, drive the end user through some kind of preg-replace, biting out all the rubbish that should not be. This is if you need to completely save the comment formatting and give the same formatting. If not, you can bite anything out of the text with regulars.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question