Basic input validation in PHP is done using the following functions.
is_string(),
is_numeric(),
is_float(),
is_array(), and
is_object().
Each of these functions take a variable and return true if that variable is of the appropriate type.
The three basic validation checks we should do.
After the basic check, we can do more check, such as integer value range, the string length, count of array elements, etc.
There are eleven CTYPE functions in total.
they work in the same way as is_numeric()
.
Function | Meaning |
---|---|
ctype_alnum() | Matches A?Z, a?z, 0?9 |
ctype_alpha() | Matches A?Z, a?z |
ctype_cntrl() | Matches ASCII control characters |
ctype_digit() | Matches 0?9 |
ctype_graph() | Matches values that can be represented graphically |
ctype_lower() | Matches a?z |
ctype_print() | Matches visible characters (not whitespace) |
ctype_punct() | Matches all non-alphanumeric characters (not whitespace) |
ctype_space() | Matches whitespace (space, tab, new line, etc.) |
ctype_upper() | Matches A?Z |
ctype_xdigit() | Matches digits in hexadecimal format |
<?PHP
$var = "123456789a";
print (int)ctype_digit($var);
?>
The following code checks
whether the $Age
variable has a numeric value between 18 and 30.
if (isset($Age)) { if (is_numeric($Age)) { if (($Age > 18) && ($Age < 30)) { print " input is valid"; } else { print "Sorry, you're not the right age!"; } } else { print "Age is incorrect!" } } else { print "Please provide a value for Age."; }