Search code examples
phpvalidationurlinputfilter-var

Defense with filter_var


I started learning web development and found this :

filter_var('php://', FILTER_VALIDATE_URL);

But they said this :

The flaw in the above is that the filter options have no method of limiting the URI scheme allowed and users’ expect this to be one of http, https or mailto rather than some generic PHP specific URI. This is the sort of generic validation approach we should seek to avoid at all costs.

Source : Input Validation

My questions :

  • I still don't understand why it is to avoid ?
  • Can anyone please give examples of attacks to this that i can simulate ?

Note : This is my first post here so am sorry if it has many or vagues questions.

Thank you.


Solution

  • var_dump(filter_var('testing://123.com', FILTER_VALIDATE_URL));  
    

    is not false. That is your answer :) You don't want to say ok to a url that is not in a registered scheme.

    So that comment essentially means that even though filter_var will scan for a proper URL format, it will not be able to correctly judge whether the URL Scheme is good or not, and a lot of bad urls can still pass through since this is generic. It is just like saying a US phone number is 10 digits, yes ok if that is the only check then 1111111111 is also a valid phone number?

    But that does not mean this is useless, you can always add a little more to your if condition to cater for that so that comment is not by any means end of the world. You can improve that check by something like

      if(filter_var($url, FILTER_VALIDATE_URL) && parse_url($url, PHP_URL_SCHEME)=="http")