Filtering PHP form inputs - three ways, but which should you use?
Archive - Originally posted on "The Horse's Mouth" - 2012-11-18 21:08:20 - Graham Ellis
There's a vital need to validate user inputs in PHP - to make sure that users have put something sensible into the boxes on your forms. And there are multiple ways of doing this:
a) You can check the incoming strings against regular expressions. In the old days you may have used the ereg functions, but these days you would use preg functions - slighly more complex, but more powerful and quicker. And the ereg functions have been deprecated. Using regular expressions, you need to define yourself what a particular string should look like - so you have a great flexibility
b) From PHP 5.2, you can use the filter_var function to filter what's in a variable. It will return FALSE if there's no match, or the value that the variable contains if it does match. For example, "does $sample contain an integer?": $result = filter_var($sample, FILTER_VALIDATE_INT);
And (sample program [here]) you get results like: Looking at 404
Integer result - 404
int(404)
and Looking at Graham Ellis
NOT an Integer
bool(false)
c) If you're using the Zend Framework, there's a validation element available within each form component / widget and you can use that to check is the form have been validly filled in.
So - which of these should you use? If you're using the MVC (Model View Controller) approach, using the Zend Framework, then it's logical to use the functions that are provided by the framework. For major systems, some sort of framework is an excellent idea - whether you use Zend, one of the others, or routines that you write yourself (your own framework) is up to you. If you use your own, then you'll be coding one of the other two options, once only, within your own framework setup as part of your standard.
filter_var is an excellent tool to use for checking specific types - email addreses, integers, IP addresses and the like; they're coded into PHP's functions so you san save yourself a great deal of work in formulating regular expressions, and you know they'll be updated and maitained with future releases as standards may change, rather than you having to update regular expressions yourself.
For the application-specific cases (and that include things like UK postcodes), you can either use preg routines directly, or you can flag filter_var to work with regular expressions, and pass them in.