I am upgrading the security of an existing site (so can't redo everything with a framework that has xss functions built in), so I am looking for a way to protect against XSS attacks such as the ones listed by OWASP here.
At the moment I use htmlspecialchars($text, ENT_QUOTES, 'UTF-8');
for output into HTML, json_encode
for JS and HTMLPurifier for data containing HTML tags but am concerned this is not enough/correct. I am looking for a function that I can use like:
<div><?php echo escape_for_html($text); ?></div>
<img src="<?php echo escape_for_attribute($text); ?>">
After some research it seems solutions like xss_clean, ESAPI and PHPSEC are either no longer being maintained or not recommended. How can I protect against xss when echoing into tag attributes (including urls), JavaScript and CSS?
<br/>
or
s in one place, and not in the other. However, if you were to usewhite-space: pre-wrap
in your CSS that would not be necessary, and you could revert back to a shared encoding function.</script
is replaced with<\/script
. (case insensitive) This is very important.href
is just as dangerous as allowing a customonclick
. (XSS) In such cases, it is important restrict the input, not just encode it. For plain text, such as thetitle
attribute, this is not an issue.filter_var($input, FILTER_VALIDATE_URL);
cover the customhref
to make sure its an url and not script? Then through htmlspecialchars as normal.