Practical Web Programming

Saturday, December 20, 2008

PHP: Checking If Email is Valid with filter_var Function

In PHP 4, checking if an email is valid uses regular expressions. But with PHP 5, you can use the filter_var function. This function returns the filtered data, or false if the filter fails.

Here's the syntax.

mixed filter_var ( mixed $variable [, int $filter [, mixed $options ]] )

Where:
variable = Value to filter.
filter = ID of a filter to use. Defaults to FILTER_SANITIZE_STRING.
options = Associative array of options or bitwise disjunction of flags.


Here's how to use the function.

if (filter_var(trim($email), FILTER_VALIDATE_EMAIL))
{
echo $email . " is valid.";
}
else
{
echo $email . " is invalid.";
}

0 comments:

Recent Post