What if you don't want to strip HTML tags, but you still want to render them harmless? You can use the htmlentities function instead, which encodes HTML tags. For example, <B>Charles</B> would be converted to <B>Charles</B>, which a browser will display as the text "<B>Charles</B>". You can see this at work in phpencode.php, Example 6-14. Example 6-14. Encoding HTML tags, phpencode.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 = htmlentities($_REQUEST["Name"]); echo $ok_text; } function display_welcome() { echo "<FORM METHOD='POST' ACTION='phpencode.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 data with HTML tags, as in Figure 6-18, the echoed text displays those HTML tags as in Figure 6-19but they're just text, not HTML. Figure 6-18. Text with HTML tags.Figure 6-19. Encoding HTML tags. |