Difference between htmlentities and htmlspecialchars

The twin functions htmlentities() and htmlspecialchars() both do the same basic job. You use them when you are displaying data, especially user input data, to:

  • prevent the use of JavaScript for cross site scripting (XSS) attacks
  • prevent the use of HTML that may otherwise break the page
  • permit the display of special reserved HTML characters such as angle brackets

Try dropping a series of closing div or table tags in the middle of your page and you will see your layout break in creatively horrifying new ways.

The character encoding of the page does become an small issue. For output as UTF-8 use htmlspecialchars() since htmlentities() will butcher certain UTF-8 characters.

Neither of the functions should be used to try to prevent SQL injection attacks since there are superior alternatives such mysql_real_escape_string().

To sum up:

htmlspecialchars() htmlentities()
converts certain characters (ampersand, less than, greater than, double quote, single quote) converts all special HTML characters into their HTML entities equivalents
safely used with UTF-8 safely used with ISO-8859-1
undo with htmlspecialchars_decode() undo with html_entity_decode()
faster slower
About author

Reli4nt is a business manager and web developer and the JP behind The JPProject. He is a proverbial jack-of-all-trades-master-of-none, and an all around simple and down to earth kind of guy.