I am wondering where the best place to filter user submitted input is. In regards to filter, I am talking about filter_var and filter_input.
I’ve come up with three scenarios:
- Filter data from POST/GET, and pass filter data to function which takes it as-is.
- Take raw data from POST/GET, and pass as-is to function where the function filters it.
- Filter data from POST/GET, and filter is a second time in the function.
Each of these methods has its advantages and disadvantages. I was looking for some insight into which may be best or standard practice.
Method 1 passes sanitized data to the function, and thus functions can be smaller not having to sanitize everything coming in. The downfall is if any other place your function is called and the data isn’t sanitized, this can lead to problems. This simply requires good coding practice to remember to sanitize everything before passing to a function.
Method 2 you will never have to worry about your function dealing with unsanitized data, but the functions will be bigger.
Method 3 is the safest, but is wasteful. More code is written, and data may be sanitized multiple times as it passes through possibly various functions, wasting CPU resources and time.
From the above-mentioned scenarios, 1 & 2 are applicable for good practice. While number 3 is unnecessary to filter input data twice as you said it waste resources.
Thus, scenario 1 or 2; it depends on what situation you are dealing with.