You want to securely 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.
Pass user input through htmlentities() before displaying it, as in Example 9-18.
Example 9-18. Escaping HTML
1 2 |
print 'The comment was: '; print htmlentities($_POST['comment']); |
PHP has a pair of functions to escape HTML entities. The most basic is htmlspecial chars(), which escapes four characters: < > ” and &. Depending on optional parameters, it can also translate ‘ instead of or in addition to “.
For more complex encoding, use htmlentities(); it expands on htmlspecialchars() to encode any character that has an HTML entity.
Example 9-19 shows htmlspecialchars() in action.
Example 9-19. Escaping HTML entities
1 2 3 4 |
$html = "<a href='fletch.html'>Stew's favorite movie.</a>\n"; print htmlspecialchars($html); // double-quotes print htmlspecialchars($html, ENT_QUOTES); // single- and double-quotes print htmlspecialchars($html, ENT_NOQUOTES); // neither |
Example 9-19 prints:
1 2 3 |
<a href='fletch.html'>Stew's favorite movie.</a> <a href='fletch.html'>Stew's favorite movie.</a> <a href='fletch.html'>Stew's favorite movie.</a> |
By default, both htmlentities() and htmlspecialchars() use the UTF-8 character set (as of PHP 5.4.0. Before that, the default was ISO-8859-1).
To use a different character set, pass the character set as a third argument. For example, to use BIG5, call htmlenti
ties($string, ENT_QUOTES, “BIG5”).