18

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);

Community
  • 1
  • 1
Charles Sprayberry
  • 7,741
  • 3
  • 41
  • 50
  • 1
    `htmlentities`/`htmlspecialchars` allow you to prevent double encoding entities by setting the 4th param to `false`. I don't if it is possible to achieve that via `filter_var`. – ryanve Nov 06 '12 at 09:56

1 Answers1

11

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.

Stephen
  • 18,597
  • 4
  • 32
  • 33
  • 1
    I figured it would be something like this for the lack of adoptions. But, then why did the PHP internal team feel the need to create `filter_var` if there isn't something wrong with the `html*` methods? – Charles Sprayberry Aug 05 '11 at 22:34
  • 1
    Because filter_var does a lot more than just HTML escaping. – Stephen Aug 05 '11 at 22:53
  • Ok, then why the need to add this specific functionality to `filter_var()`? – Charles Sprayberry Aug 05 '11 at 23:26
  • 11
    Because it allows developers to use the same filter method with different arguments to do various kinds of filtering and sanitisation, rather than having to call different methods with different arguments. – Stephen Aug 06 '11 at 00:23