How to Validate Email Addresses in a PHP Script

Technology Communication Networking Webinar Concept
Enis Aksoy / Getty Images

Email addresses: easy to create, difficult to type.

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:

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\"").

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:

You can also filter an email address straight from the web form (assuming the email address was captured in field with the name "email"):