S
S
sorry_i_noob2018-08-10 00:27:41
PHP
sorry_i_noob, 2018-08-10 00:27:41

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

4 answer(s)
F
FoxIK, 2018-08-12
@FoxIK

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'));

H
hell, 2018-08-10
@hell

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.

R
Roman Terekhin, 2018-08-10
@RomaZveR

In this case, it is better to look towards bb-codes.

I
Igor, 2018-08-10
@Lopar

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 question

Ask a Question

731 491 924 answers to any question