PHP 5.2.0 and up comes with a very convenient set of data filtering functions. These functions allow you to easily validate common things such as emails and URLs, that would otherwise require complex regular expressions that don't always work. This tutorial will focus on the simplest function filter_var().
The filter_var function looks like this:
mixed filter_var ( mixed $variable [, int $filter= FILTER_DEFAULT [, mixed $options ]] )
- $variable - Input value to validate
- $filter - Filter ID to use for validation
- $options - Option flags for filter, or callback functions for callback filter
- Returns - Filtered data or FALSE if filter fails
There are basically two types of filters you can use, "sanitize" and "validate" filters. Sanitize filters basically remove unwanted characters from a string so it is "safe" for certain uses. Validate filters are used just to check is the text is valid for the specified filter and returns FALSE if it is not. There is also a filter called FILTER_CALLBACK that allows you to create custom functions to run on the input text.
Here are some examples of usage:
Code: Select all
// check if an email address is valid
$email = "[email protected]";
if(filter_var($email, FILTER_VALIDATE_EMAIL) !== false) {
echo "Email is valid!";
}
// check if URL is valid and includes scheme and host
// (note use of "|" character to use multiple flags)
$url = "http://example.com";
if(filter_var($url, FILTER_VALIDATE_URL, FILTER_FLAG_SCHEME_REQUIRED | FILTER_FLAG_HOST_REQUIRED) !== false) {
echo "URL is valid!";
}
// remove unsafe characters from an email address
$email = "someone@s()ome;where.com";
echo filter_var($email, FILTER_SANITIZE_EMAIL); // outputs: [email protected]