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 name 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, a vulnerability exists whenever you output un-escaped data. For example:

<?php

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, all that is necessary is that you escape your output:

<?php

$html = array(  );

$html['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 only output the filtered username, no XSS vulnerability exists.

Just be sure that you don’t depend upon filtering as your primary safeguard against XSS, because it doesn’t ...

Get Programming PHP, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.