I’ve been ‘sprinkling’
htmlentities($user_input, ENT_QUOTES, 'UTF-8')
throughout my views, everywhere I echo data that a user had the chance to enter in my app.
This is very tedious and I’m wondering if using HTMLPurifier in my controllers would be a safe substitute to using htmlentities in every echo on the view.
I’ve noticed that HTMLPurifier alone will, for example, try to close an open <div> instead of removing it, so if some smartass entered his name as Johnny<div> and I echo it in my view, it breaks my entire layout.
But if instead I use htmlentities alone I get
Johnny<div>
and my layout is preserved.
So I’m wondering if this is an issue with HTMLPurifier config or if the best practice is to use it in tandem with htmlentities.
I understand HTMLPurifier has other functions re compliance and valid HTML, but I’m mostly concerned with XSS.
What do you think?
If you are concerned about XSS then use
htmlspecialchars(there’s no reason to use the full-blownhtmlentitiesfor that) and you are golden:HTMLPurifier is only meaningful if you want to allow some HTML capability while still preventing XSS. But as any other piece of code, there’s the possibility that it might not work as advertised at some point. Personally, I wouldn’t go there.
Update:
Yes,
htmlspecialcharsdoes support additional flags (includingENT_QUOTES). However,ENT_QUOTESis only needed if:So for example, you would not need
ENT_QUOTEShere:or here:
You would need it here: