Validating Data
Validating data using the Filter extension is accomplished using the
filter_var()
function in conjunction with one of seven available filters. For instance, to validate an email address, use the FILTER_VALIDATE_EMAIL
validation filter:$email = "[email protected]";
if (filter_var($email, FILTER_VALIDATE_EMAIL)) { echo "Valid email address!"; } else { echo "Invalid email address!"; }
Validating an Alphanumeric String
Oddly, the Filter extension doesn’t offer a filter for validating or sanitizing strings consisting solely of alphanumeric characters. However, thanks to the
FILTER_VALIDATE_REGEXP
extension, it’s trivial to create your own solution. Returning to the maliciously malformed recovery key used in the opening example, you can create a regular expression which will return TRUE
only if the provided string consists of letters and numbers as demonstrated here:$recoveryKey = "' OR ''='";
if (filter_var($recoveryKey, FILTER_VALIDATE_REGEXP, array('options' => array('regexp' => "/^[a-zA-Z0-9]+$/")))) { echo "Valid recovery key"; } else { echo "Invalid recovery key"; }
Validating an Integer Value
The Filter extension also offers a validation filter named
FILTER_VALIDATE_INT
, which can be used to ensure that a value is a valid integer. You can optionally pass an integer range to ensure that the value falls within a defined boundary. For instance, if you wanted to collect age-related information from your users, you’d presumably want to allow only users aged between 13 and 100 or so years (the lower limit is in order to comply with COPPA and the upper limit simply a reasonable upper limit in terms of practical life span). You can set this range using the FILTER_VALIDATE_INT
filter like this:if (filter_var($age), FILTER_VALIDATE_INT, array('options' => array('min_range' => 13, 'max_range' => 100))) { echo "Valid age!"; } else { echo "Invalid age!"; }
Other Validation Resources
PHP’s Filter extension is only one of the latest of many validation-specific solutions at your disposal. A great number of useful string-related functions are found in PHP’s Strings library. When sending data to a MySQL query, be sure to use prepared statements in order to properly escape any special characters, which could be used to interfere with the query’s proper functioning. If you’re a Zend Framework user, then I highly recommend checking out the Zend_Filter component.
With so many options at your disposal, incorporating a sound approach to data validation within your next project should be a trivial part of the process, allowing you spend even more time investigating new technologies!
About the Author
Jason Gilmore is the founder of the publishing and consulting firm WJGilmore.com. He also is the author of several popular books, including “Easy PHP Websites with the Zend Framework”, “Easy PayPal with PHP”, and “Beginning PHP and MySQL, Fourth Edition”. Follow him on Twitter at @wjgilmore.