Preventing Cross-Site Scripting

You want to securily display user-entered data on an HTML page. For example you want to allow users to add comments to a blog post without worrying that HTML or Javascript in a comment will cause problems.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="EN" lang="EN">
<head>
<title>PHP</title>
<meta Name="Author" Content="Hann So">
</head>
<body>
<p>
<?php
function display_form() {
echo <<<HTML
<form action = "$_SERVER[SCRIPT_NAME]" method="post">
First Comment: <textarea name="comment1" rows="5" cols="50">
<font color=blue size=+3>Hello
</textarea><br />
Second Comment: <textarea name="comment2" rows="5" cols="50">
<font color=blue size=+3>Hello</font>
</textarea><br />
<input type="submit" value="submit" />
</form>
HTML;
}

// Make sure that the first_name field exists before checking its length
if (isset($_POST['comment1'])) {
	echo 'The first comment was: ', $_POST['comment1'], '<br />';
	echo 'The second comment was: ', htmlentities($_POST['comment2']), '<br />';
}
else {
	display_form();
}
?>
</p>
</body>
</html>

View the effect


Forms | Introduction | Creating a Form | Superglobals | Processing Form Input | Required Fields | Numbers | Drop-Down Menus | Radio Buttons | Checkboxes | Periods in Their Names | Preventing Cross-Site Scripting | Stripping out Slashes | Redirecting the User | Server Information | Determining Browser Type | Sticky Forms
© 2008: Hann So
email: hso@voyager.deanza.edu