Cross-site scripting (XSS) has become the most common web application security vulnerability, and with the rising popularity of Ajax technologies, XSS attacks are likely to become more advanced and to occur more frequently.
The term cross-site scripting derives from an old exploit and is no longer very descriptive or accurate for most modern attacks, and this has caused some confusion.
Simply put, your code is vulnerable whenever you output data not properly escaped to the output’s context. For example:
This is an extreme example, because
$_POST is obviously neither filtered nor
escaped, but it demonstrates the vulnerability.
XSS attacks are limited to only what is possible with client-side
technologies. Historically, XSS has been used to capture a victim’s
cookies by taking advantage of the fact that
document.cookie contains this
In order to prevent XSS, you simply need to properly escape your output for the output context:
You should also always filter your input, and filtering can offer a redundant safeguard in some cases (implementing redundant safeguards adheres to a security principle known as Defense in Depth). For example, if you inspect a username to ensure it’s alphabetic and also only output the filtered username, no XSS vulnerability exists.
Just be sure that you don’t depend upon filtering as your primary safeguard ...