When you're validating data, here's something to watch out forHTML in a user's text, especially if you're going to display that text. Malicious users can put some nasty HTML (including JavaScript) into submitted text, which would be executed if you display that text in a browser. You can use the PHP strip_tags function to remove all HTML tags from text, as shown in phpstrip.php, Example 6-13. Example 6-13. Removing HTML tags, phpstrip.php<HTML><HEAD><TITLE>Using Text Fields</TITLE></HEAD> <BODY><CENTER><H1>Using Text Fields</H1> <?php $errors = array(); if(isset($_REQUEST["seen_already"])){ validate_data(); if(count($errors) != 0){ display_errors(); display_welcome(); } else {process_data();} } else { display_welcome(); } function validate_data() { global $errors; if($_REQUEST["Name"] == "") { $errors[] = "<FONT COLOR='RED'>Please enter your name</FONT>";} } function display_errors() { global $errors; foreach ($errors as $err){ echo $err, "<BR>";} } function process_data() { echo "Your name is "; $ok_text = strip_tags($_REQUEST["Name"]); echo $ok_text; } function display_welcome() { echo "<FORM METHOD='POST' ACTION='phpstrip.php'>"; echo "What's your name?<BR>"; echo "<INPUT NAME='Name' TYPE='TEXT'>"; echo "<BR><BR>"; echo "<INPUT TYPE='SUBMIT' VALUE='Submit'>"; echo "<INPUT TYPE='HIDDEN' NAME='seen_already' VALUE='hidden_data'>"; echo "</FORM>"; } ?></CENTER></BODY></HTML> Now if the user enters text with HTML tags, as in Figure 6-16, those tags will be removed automatically and the text made safe, as you see in Figure 6-17. Figure 6-16. Text input with HTML tags.Figure 6-17. Stripping HTML tags. |