Preventing XSS in PHP

Cross Site Scripting (XSS) is one of the most common forms of security attacks that happens against websites. This article will show you simple methods of preventing XSS in PHP.

The attack focuses on injecting code which can happen if user input isn’t correctly sanitised or escaped when being output to the browser. This can cause the code to save harmful data or perform a malicious action within the user’s browser.

Using a few in-built PHP functions, the risk of an XSS attack can be greatly reduced.

To filter and sanitise user input, you can use the filter_var() function and pass in the relevant filter as the second parameter.

$email = "";

// Remove all illegal characters from email
$email = filter_var($email, FILTER_SANITIZE_EMAIL);

// Validate e-mail
if (!filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
    echo("$email is a valid email address");
} else {
    echo("$email is not a valid email address");

An extract of some of the sanitisation and validation filters can be seen below.


The first method of safely outputting user data involves using the htmlspecialchars() function. This function converts special characters to HTML entities. The below shows the list of characters that get converted.

Preventing XSS in PHP

An example of the function in action can be seen below:

Preventing XSS in PHP

Note that htmlspecialchars() will only convert the special characters listed above and not anything else. For other entities, you should use the htmlentities() function.

The second method involves using the htmlentities() function. This function is identical to htmlspecialchars() in all ways, except with htmlentities(), all characters which have HTML character entity equivalents are translated into these entities.

Preventing XSS in PHP

You can also specify a flag as a second parameter. For example, ENT_QUOTES ensures that both single and double quotes get converted.

Preventing XSS in PHP

Lastly, the strip_tags() function strips HTML and PHP tags from a string.

Preventing XSS in PHP

The strip_tags() function also gives you the ability to keep tags within the string from being removed. By passing in a second parameter, you can add tags that you would like to preserve in the string, like so:

Preventing XSS in PHP

Because strip_tags() does not actually validate the HTML, partial or broken tags can result in the removal of more text/data than expected.

Note: This article is based on PHP version 5.5.