Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

filter_var vs htmlentities vs htmlspecialchars

Disclaimer

This is not a question about whether we should be escaping for database input. This is strictly looking at the technical differences between the three functions in the title.

There is this question discussing the difference between htmlentities() and htmlspecialchars(). But, it doesn't really discuss filter_var() and the information I found on Google was more along the lines of "Make sure you escape user input before it is echo'd!"

My questions are:

  • Why are htmlspecialchars() and htmlentities() commonly used over filter_var()?
  • Is there some performance hit from using filter_var()?
  • Is filter_var() not as secure as the other two options?
  • Is there any other reason NOT to use the following to encode user input before being echod

filter_var($var, FILTER_SANITIZE_FULL_SPECIAL_CHARS);

like image 386
Charles Sprayberry Avatar asked Aug 05 '11 20:08

Charles Sprayberry


People also ask

What's the difference between Htmlentities () and htmlspecialchars ()?

Difference between htmlentities() and htmlspecialchars() function: The only difference between these function is that htmlspecialchars() function convert the special characters to HTML entities whereas htmlentities() function convert all applicable characters to HTML entities.

Is Htmlentities enough to prevent XSS?

In answer to your question, you should use htmlentities() when outputting any content that could contain user input or special characters. Show activity on this post. htmlspecialchars() is more than enough. htmlentities is for different use, not preventing XSS.

What is Htmlspecialchars?

Description. The htmlspecialchars() function is used to converts special characters ( e.g. & (ampersand), " (double quote), ' (single quote), < (less than), > (greater than)) to HTML entities ( i.e. & (ampersand) becomes &amp, ' (single quote) becomes &#039, < (less than) becomes &lt; (greater than) becomes &gt; ).

Does Htmlspecialchars prevent XSS?

Using htmlspecialchars() function – The htmlspecialchars() function converts special characters to HTML entities. For a majority of web-apps, we can use this method and this is one of the most popular methods to prevent XSS. This process is also known as HTML Escaping.


1 Answers

My guess (about lack of adoption) would be it's simply because the Filter extension is only enabled by default since v5.2, whereas the html* methods have been around longer.

like image 65
Stephen Avatar answered Sep 25 '22 02:09

Stephen