Much can go wrong. Much can look all wrong and be all right. Much can look right and not work at all.
Getting email addresses you collect — for a newsletter, say, or for password retrieval — to at least conform to standards (if not ensure ) is crucial, of course, and extremely tricky.
Fortunately, PHP (5 and later) comes with a handy set of functions and filters that make testing for email address validity a snap.
Validate Email Addresses in a PHP Script
To validate an email address for correctness (not checking whether the address is actually working and read) in PHP:
- Build email validation into the HTML if you use a web form where people enter email addresses.
- Use the FILTER_VALIDATE_EMAIL PHP email validation filter. (See below for examples.)
FILTER_VALIDATE_EMAIL PHP Email Address Validation Caveats
Note that FILTER_VALIDATE_EMAIL will validate email addresses that contain domains and top-level domains that do not exist. If you want to avoid these, you can test for top-level domains that are more than 4 characters long (which will erroneously throw out ".museum"), or for domain names that are either 2 characters long (all the country top-level domains) or one of the known top-level domains (which you will have to update as the list changes).
FILTER_VALIDATE_EMAIL will erroneously balk at email addresses with long domain names (64 characters or more), and at email addresses with escaped characters (such as "me\"@example.com"). To avoid these false positives, you can turn to a class like php-email-address-validation.
FILTER_VALIDATE_EMAIL Email Address Validation Examples
Assuming $email_address holds the address to be checked, you could try its validity using:
<?php
$email_address = "me@example.com";
if (filter_var($email_address, FILTER_VALIDATE_EMAIL)) {
// The email address is valid
} else {
// The email address is not valid
}
?>
You can also filter an email address straight from the web form (assuming the email address was captured in field with the name "email"):
<?php
$email_address = filter_input(INPUT_GET, 'email', FILTER_VALIDATE_EMAIL);
if (!$email_address) {
// The email address is not valid
}
?>

