Create a page called crossform.html and paste this into it:

<form action="crossprocess.php" method="post">
    <input type="text" name="message">
    <input type="submit">

Now create the PHP page to handle the form data and call it crossprocess.php.  Put this under the h1:

header("X-XSS-Protection: 0;");
echo $message;

Test the pages by typing anything into the field and pressing the button.  Then go back to the form and paste this into it as if the user had typed it:

<script type="text/javascript">window.location.assign('');</script>

Your browser has just been hijacked and sent to another site.  A clever hacker could make the new site look exactly like yours but use it to get information from the user.  Imagine that code being used on a bank site and the hacker then being able to get the user's name and password as they assumed they were still on that site.

You do not need to type or paste the code in you can just put a script element in which refers to code on another site (try pasting this):

<script type="text/javascript" src="uploads/evil.js"></script>

This is cross-site scripting and was used a lot until developers started protecting against it.  Some browsers also now block it but that was turned off by the first line of PHP above.

Using htmlspecialchars

Any time there is data coming from the user (or which might be compromised another way) you need to use this function before displaying that data on a page.  Even if the data is coming from a database you might want to use it just in case the database is compromised.

In crossprocess.php replace the $_POST line with this variation:


Try pasting either example of cross-site scripting code from above into the form again but this time it is safe.  The htmlspecialchars() function has replaced all HTML reserved symbols with HTML entities.  To see the entities look at the source code of crossprocess.php by right clicking in the browser.

When to do it

This function is designed to be used before you display any data to the user.  So the best bet is probably to get into the habit of protecting every piece of data which has come from a form, cookie etc. before you display it.    If the data is being stored in a database it will be made SQL-safe another way but that way will not help with XSS.  So it is probably worth sanitising the data with htmlspecialchars() before it goes into the database just in case it is ever displayed.

The only situation where you might not use htmlspecialchars() is if you actually wanted the user to input HTML code to a form.  Then you would have to find another way to remove potentially dangerous code without breaking their code.  All content management systems need some way of doing this.