Validating Input
Any sensible site should include server-side validation of variables, because they are much harder to hack, and they will work no matter what browsers your visitors are using.
Basic input validation
in PHP is done using the functions is_string()
, is_numeric()
, is_float()
, is_array()
, and is_object()
. Each of these functions take just one parameter, a variable of their namesake, and return true
if that variable is of the appropriate type. For example, is_numeric()
will return true
if the variable passed to it is a number, and is_object()
will return true
if its variable is an object. There is one other function of this type that works the same way but is useless for validation, and that is is_resource()
—it's mentioned here for the sake of completeness.
The three basic validation checks you should conduct on input are whether you have each of your required variables, whether they have a value assigned, and whether they are of the type you were expecting. From there, you can conduct more complicated checks, such as whether the integer values are in the range you would expect, whether the string values have enough characters, whether the arrays have enough elements, etc.
Here are some examples:
// is the $Age variable set with a numeric value between 18 and 30? if (isset($Age)) { if (is_numeric($Age)) { if (($Age > 18) && ($Age < 30)) { // input is valid } else { print "Sorry, you're not the right age!"; } } else { // empty or non-numeric print "Age is incorrect!" } } ...
Get PHP in a Nutshell now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.