March 24, 2011, 10:32 a.m.
posted by stackme
Preventing Cross-Site Scripting
Pass user input through htmlentities( ) before displaying it, as in Figure.
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. Figure shows htmlspecialchars( ) in action.
Escaping HTML entities
<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 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').