— Preventing Cross-Site Scripting – PHP #QuickTip

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.

For this you can pass user input through htmlentities(  ) before displaying it.

Escaping Html

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

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.

Escaping Html Entities

<?php
$html = "<a href='mypaaji.com'>sunny's site.</a>\n";
print htmlspecialchars($html);                // double-quotes
print htmlspecialchars($html, ENT_QUOTES);    // single- and double-quotes
print htmlspecialchars($html, ENT_NOQUOTES); // neither
?>

Output

&lt;a href=&quot;mypaaji.com&quot;&gt;sunny's site.&lt;/a&gt;
&lt;a href=&quot;mypaaji.com&quot;&gt;sunny&#039;s site.&lt;/a&gt;
&lt;a href="mypaaji.com"&gt;sunny's site..&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′).

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 char-
acter that has an HTML entity.


blog comments powered by Disqus