Many Web applications take the information submitted by a user, store it in a database, and then redsiplay that information on another page. If malicious code entered into a form were redispalyed in a browser, it could create popups, steals cookies, or redirects to other sites. Such atatcks are known as cross site scripting(XSS).
Use one of the following three functions to handle XSS attacks:
<!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>Preventing XSS Attacks</title> <meta Name="Author" Content="Hann So"> </head> <body> <p> <?php if (isset($_POST['submit'])) { process_form(); } else { display_form();// display form for the first time } function display_form() { echo <<<HTML <h2>XSS Attacks</h2> <form action = "$_SERVER[SCRIPT_NAME]" method="post"> Enter anything (HTML, CSS, Javascript): <textarea name="comments" rows="8" cols="40"> "See what you can do." <script language="javascript"> alert('I got you!'); </script> <font color=blue size=+3>Using HTML tags</font> </textarea> <br /> <input type="submit" name="submit" value="Submit" /> </form> HTML; } function process_form() { //display to see what we got from the form for the comments echo "Original text:<br />"; echo "{$_POST['comments']}<br />"; // apply htmlspecialchars() echo "<p>After applying htmlspecialchars():</p>"; echo htmlspecialchars($_POST['comments']); // apply htmlentities() echo "<p>After applying htmlentities():</p>"; echo htmlentities($_POST['comments']); // apply strip_tags() echo "<p>After applying strip_tags():</p>"; echo strip_tags($_POST['comments']); echo "<p><a href=\"$_SERVER[SCRIPT_NAME]\">Try again?</a></p>"; } ?> </p> </body> </html> |