When to use filter_input()

Well, there are going to be differing opinions.

My take is that you should always use it (or, the filter extension in general). There are at least 3 reasons for this:

  1. Sanitizing input is something you should always do. Since the function gives you this capability there is really no reason to find other ways of sanitizing input. Since it is an extension the filter will also be much faster and most likely safer than most PHP solutions out there, which certainly does not hurt. The only exception is if you need a more specialized filter. Even then you should grab the value using the FILTER_UNSAFE_RAW filter (see #3).

  2. There are a lot of goodies in the filter extension. It can save you hours from writing sanitizing and validation code. Of course, it does not cover every single case, but there is enough so that you can focus more on specific filtering/validating code.

  3. Using the function is very good for when you are debugging/auditing your code. When the function is used you know exactly what the input will be. For example, if you use the FILTER_SANITIZE_NUMBER_INT filter then you can be sure that the input will be a number — no SQL injections, no HTML or Javascript code, etc. If you, on the other hand, use something like FILTER_UNSAFE_RAW then you know that it should be treated carefully, and that it can easily cause security problems.

Leave a Comment