2

How can I totally prevent xss-attacks in PHP? This is assuming I do not care for any HTML tags or other formatting. Would it be enough to just run strip_tags and have it be completely safe?

4
  • possible duplicate of Is strip_tags() vulnerable to scripting attacks? Commented May 9, 2011 at 8:07
  • 7
    @edem: XSS vulnerabilities are language independent. Commented May 9, 2011 at 8:09
  • I know but PHP is more vulnerable. Commented May 11, 2011 at 9:38
  • There is no simple solution to totally prevent XSS. It strongly depends on the context. Commented Apr 16, 2015 at 6:55

2 Answers 2

4

Both htmlspecialchars() and strip_tags() are considered safe for cleaning user input for output on a HTML page.

Related:

Sign up to request clarification or add additional context in comments.

5 Comments

Depends on the context. Are you outputting it between tags, in css, in javascript, in a javascript string inside the onclick event etc.
if input have html code this functions works but if input contain code like this : javscript:alert(1) this functions can't protect u from xss ...
@Pouya now that's just nonsense. How would the attacker execute the javascript if there are no HTML elements to put it in?
@Pekka htmlspecialchars and other function like that just convert or remove html chars , but javascript can be execute without any html char! php code like this is vulnerable : <img src="<?php echo htmlspecialchars($_GET['img']); ?>"> tell me this input: javscript:alert(1) execute or not !
@Pouya yes, that would create a vulnerability. It's arguably a different scenario though. The methods above provide sufficient safety when outputting HTML in the body.
1

The easiest way is to simply prevent any users from entering HTML tags. If you strip_tags() or htmlspecialchars() all user input then there is no way to introduce a <script> tag.

If you want to allow limited markup, then you can use a bbcode-like syntax (finding a PHP library for doing this shouldn't be hard, though I've never done this myself so don't have any recommendations on that front), or you could use HTMLpurifier to restrict the markup that users are allowed to enter.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.