Difference between htmlentities and htmlspecialchars in PHP
What is the difference in htmlentities() and htmlspecialchars() function in PHP?
htmlspecialchars() is a subset of htmlentities().
While htmlentities converts “all applicable characters to HTML entities”, htmlspecialchars() only converts …
- ‘&’ (ampersand) becomes ‘&’
- ‘”‘ (double quote) becomes ‘"’ when
ENT_NOQUOTES
is not set. - “‘” (single quote) becomes ‘'’ (or ') only when
ENT_QUOTES
is set. - ‘<‘ (less than) becomes ‘<’
- ‘>’ (greater than) becomes ‘>’
as referenced from the PHP manual.
Both functions are used to perform ‘output escaping’ to make webpage safer against cross-site-scripting attacks. However, the book Essential PHP Security says …
“htmlentities() is the best escaping function for escaping data to be sent to the client.”
and to use the ENT_QUOTES flag and UTF-8 encoding like this …
htmlentities($userdata, ENT_QUOTES, ‘UTF-8’);
The ENT_QUOTES flag tells it to convert both double and single quotes.
The parameters of the two functions are identical.