How to Validate Email Addresses in a PHP Script

Technology Communication Networking Webinar Concept
Enis Aksoy / Getty Images

Protect the integrity of your email lists by using PHP to check the validity of an email address in a sign-up form.

Use HTML Validation

If you have the choice, err on the side of using HTML to validate email addresses directly on the web form. Build email validation into the HTML to keep both your site and its supporting filters in the same codebase.

If you cannot use HTML validation, use PHP validation.

PHP Validation

Alternatively, use the FILTER_VALIDATE_EMAIL PHP email-validation filter to weed out email addresses that contain domains and top-level domains that do not exist. Alternatively, 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.