Recipe 18.4. Avoiding Cross-Site Scripting


18.4.1. Problem

You need to safely avoid cross-site scripting (XSS) attacks in your PHP applications.

18.4.2. Solution

Escape 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. Discussion

The htmlentities( ) function replaces each character with its HTML entity, if it has one. For example, > is replaced with &gt;. 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 &gt; 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 Also

Recipe 9.10 discusses cross-site scripting prevention in the context of submitted form data.




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

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