Recipe 9.10. Preventing Cross-Site Scripting


9.10.1. Problem

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.

9.10.2. Solution

Pass user input through htmlentities( ) before displaying it, as in Example 9-19.

Escaping HTML

<?php print 'The comment was: '; print htmlentities($_POST['comment']); ?>

9.10.3. Discussion

PHP has a pair of functions to escape HTML entities. The most basic is htmlspecialchars( ), 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-20 shows htmlspecialchars( ) in action.

Escaping HTML entities

<?php $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-20 prints:

&lt;a href=&quot;fletch.html&quot;&gt;Stew's favorite movie.&lt;/a&gt; &lt;a href=&quot;fletch.html&quot;&gt;Stew&#039;s favorite movie.&lt;/a&gt; &lt;a href="fletch.html"&gt;Stew's favorite movie.&lt;/a&gt;

By default, both htmlentities( ) and htmlspecialchars( ) use the ISO-8859-1 character set. To use a different character set, pass the character set as a third argument. For example, to use UTF-8, call htmlentities($string, ENT_QUOTES, 'UTF-8').

9.10.4. See Also

Recipes 18.4 and 19.13; documentation on htmlentities( ) at http://www.php.net/htmlentities and htmlspecialchars( ) at http://www.php.net/htmlspecialchars.




PHP Cookbook, 2nd Edition
PHP Cookbook: Solutions and Examples for PHP Programmers
ISBN: 0596101015
EAN: 2147483647
Year: 2006
Pages: 445

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net