Cross Site Scripting (XSS)

Cross site scripting is one of the more prevalent security flaws found within Web applications today. According to, XSS occurs “when an attacker uses a web application to send malicious code, generally in the form of a browser side script, to a different end user.” This means that an attacker is submitting code, for example, Javascript, within a form field that could potentially redirect information, such as cookies, which store a username and password to an unknown location.

Here is an example of a simple script vulnerable to XSS and is used to fetch a news item based on an ID:


$id = $_GET[‘id’];
echo $id;


If $_GET[‘id’] contains a number, then the script will run as intended. What happens if it contains the following:

<script>window.location.href = “’ + document.cookie;</script>

If an attacker passed this simple Javascript into the $_GET[‘id’] variable and convinced a user to click it, then the script would be executed and be used to pass the user’s cookie data onto the attacker, allowing them to log in as the user.

How to prevent XSS attacks?

As mentioned earlier, you should never trust user input. Always presume that every bit of user input contains an attack. To prevent XSS attacks, you need to filter user input, removing it of HTML tags so that no Javascript can be run. The easiest way to do this is with the following PHP’s built in function:

  • strip_tags(): Used to remove HTML from a string rendering it harmless.
  • htmlentities(): Used to convert < and > to &lt; and &gt; respectively, if you do not want to remove HTML from a string.