In order of preference:
- If you are using a templating engine (e.g. Twig, Smarty, Blade), check that it offers context-sensitive escaping. I know from experience that Twig does.
{{ var|e('html_attr') }}
- If you want to allow HTML, use HTML Purifier. Even if you think you only accept Markdown or ReStructuredText, you still want to purify the HTML these markup languages output.
- Otherwise, use
htmlentities($var, ENT_QUOTES | ENT_HTML5, $charset)
and make sure the rest of your document uses the same character set as $charset
. In most cases, 'UTF-8'
is the desired character set.
Also, make sure you escape on output, not on input.