PHP: htmlspecialchars()

This entry is part 43 of 54 in the series PHP Tutorial

htmlspecialchars — Convert special characters to HTML entities.

Certain characters have special significance in HTML, and should be represented by HTML entities if they are to preserve their meanings.

For example, < will be represented by its entity as &lt.  When we enter < into the textbox, the htmlspecialchars will convert it to &lt which is safe for the web server.

This is for security reason as certain combinations of those characters could be exploited causing the web server to be compromised.


$new = htmlspecialchars("<a href='test'>Test</a>");
echo $new; // &lt;a href='test'&gt;Test&lt;/a&gt;

Try The Code

The translations/conversions performed are:

  • ‘&’ (ampersand) becomes ‘&amp;’
  • ‘”‘ (double quote) becomes ‘&quot;’ when ENT_NOQUOTES is not set.
  • “‘” (single quote) becomes ‘&#039;’ (or &apos;) only when ENT_QUOTES is set.
  • ‘<‘ (less than) becomes ‘&lt;’
  • ‘>’ (greater than) becomes ‘&gt;’
Series Navigation<< PHP: Form with a separate php script file
PHP: Radio button form >>