views:

937

answers:

3

How do I prevent XSS (cross-site scripting) using just HTML and PHP?

I've seen numerous other posts on this topic but I have not found an article that clear and concisely states how to actually prevent XSS.

+2  A: 

One of the most important steps is to sanitize any user input before it is processed and/or rendered back to the browser. PHP has some "filter" functions that can be used.

The form that XSS attacks usually have is to insert a link to some off-site javascript that contains malicious intent for the user. Read more about it here.

You'll also want to test your site - I can recommend the Firefox add-on XSS Me.

James Kolpack
What do I need to make sure I sanitize the input exactly from. Is there one particular character/string that I have to watch out for?
TimTim
@TimTim - no. **All user input** should **always** be considered as inherently hostile.
zombat
+3  A: 

Basically you need to use the function htmlspecialchars() whenever you want to output something to the browser that came from the user input.

The correct way to use this function is something like this:

echo htmlspecialchars($string, ENT_QUOTES, 'UTF-8');

Google Code University also has some very educational videos on Web Security.

Alix Axel
Is it as simple as that? If so, awesome.
TimTim
@TimTim: For most cases, yeah. However, when you need to allow HTML input things get a little trickier and if this is the case I recommend you use something like http://htmlpurifier.org/
Alix Axel
@Alix Axel, so is your answer to use htmlspecialchars or to use http://htmlpurifier.org/?
TimTim
If you need to accept HTML input use HTML Purifier, if not use `htmlspecialchars()`.
Alix Axel
Why was this down-voted?
Alix Axel
A: 

Take a look at the Writing Secure Series on AddedBytes.com

http://www.addedbytes.com/writing-secure-php/

there are a lot more things you have to do to write secure php code than just htmlspecialchars, because that doesnt protect against sql injections or anything like that.

Tom Schlick
Have you read the question title?
Alix Axel