O'Reilly logo

Programming PHP, 3rd Edition by Peter MacIntyre, Kevin Tatroe, Rasmus Lerdorf

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Cross-Site Scripting

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:

echo $_POST['username'];

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 information.

In order to prevent XSS, you simply need to properly escape your output for the output context:

$html = array(
  'username' => htmlentities($_POST['username'], ENT_QUOTES, 'UTF-8'),
);

echo $html['username'];

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required