18.4.1. ProblemYou need to safely avoid cross-site scripting (XSS) attacks in your PHP applications. 18.4.2. SolutionEscape all HTML output with htmlentities( ), being sure to indicate the correct character encoding: <?php /* Note the character encoding. */ header('Content-Type: text/html; charset=UTF-8'); /* Initialize an array for escaped data. */ $html = array(); /* Escape the filtered data. */ $html['username'] = htmlentities($clean['username'], ENT_QUOTES, 'UTF-8'); echo "<p>Welcome back, {$html['username']}.</p>"; ?> 18.4.3. DiscussionThe htmlentities( ) function replaces each character with its HTML entity, if it has one. For example, > is replaced with >. Although the immediate effect is that the data is modified, the purpose of the escaping is to preserve the data in a different context. Whenever a browser renders > as HTML, it appears on the screen as >. XSS attacks try to take advantage of a situation where data provided by a third party is included in the HTML without being escaped properly. A clever attacker can provide code that can be very dangerous to your users when interpreted by their browsers. By using htmlentities( ), you can be sure that such third-party data is displayed properly and not interpreted. 18.4.4. See AlsoRecipe 9.10 discusses cross-site scripting prevention in the context of submitted form data. |