I always use strip_tags
to prevent XSS attacks, but today I saw a post which was telling it's horribly unsafe. As the manual says, it doesn't check for malformed HTML!
Is it true?
What can I do to prevent XSS?
Information Security Stack Exchange is a question and answer site for information security professionals. It only takes a minute to sign up.
Sign up to join this communityTo prevent XSS you need to:
Validate all user input that you'll process (for example - if id GET parameter should be a number, ensure it is with e.g. PHP's is_number()
function or using Filter extension). This should not only include GET / POST parameters, but also cookie names, cookie values, HTTP headers, uploaded file names etc. Attackers can manipulate requests in many ways. If you need to accept & display HTML content from the user (e.g. in CMS application) use well-tested HTMLPurifier library to filter out Javascript & other XSS payload and leave only clean, sanitized HTML.
When displaying the value use contextual output encoding (sometimes called 'escaping'). There are different rules on how to encode user-supplied value whether it occurs in:
<div>{$_GET['id']}</div>
<div class='{$_GET['class']}'>
<script> var a = '{$_GET['id']}'</script>
<div style='background:url({$_GET['image']})'>
It's best to refer to recommended rules described in OWASP XSS Prevention Cheat Sheet. Read it thoroughly and adher to it - XSS is #2 risk to web applications today so you really need to protect from it. See also OWASP tutorial video on XSS.
<div>{$_GET['id']}</div>
and <div style="background:url({$_GET['image']})">
, or is that valid PHP?
Dec 26, 2011 at 18:48
is_int
will never work for POST/GET values, since they're always strings. ctype_digit
or, yes, the Filter extension is what you're looking for. :)
You should use contextual encoding. See the owasp xss prevention cheat sheet. You have to encode differently depending on where the output is. As an example the following input will be missed by strip_tags, yet cause xss if the output is in the value attribute of a html text input: " autofocus onfocus="alert(1)