How to Validate an Email Address in PHP?

Problem:

To subscribe in your mailing list through opt-in form, visitor enters his email address. Or, to contact you, prospect enter message with email address in the contact form. For various reasons, you deal with email addresses. What’s the use if the email address is in invalid format? You’ll never reach them. So, you need to make sure that the email addresses users enter are in valid farmats.

Solution:

You can validate email addresses with a predefined filter(FILTER_VALIDATE_EMAIL) inside the filter_var() function.

Now, you don’t need to write any complex regular expressions to check if an email address is in right format as you did before. filter_var() function does all the hard works for you. Just use the FILTER_VALIDATE_EMAIL filter inside the function, that’s all. See some examples how it works-

<?php
echo filter_var('test@yahoo.com', FILTER_VALIDATE_EMAIL) ? "Valid email format": "Invalid email format"; echo "<br />";
echo filter_var('test.abc@abc.com', FILTER_VALIDATE_EMAIL) ? "Valid email format": "Invalid email format"; echo "<br />";
echo filter_var('test@yahoo', FILTER_VALIDATE_EMAIL) ? "Valid email format": "Invalid email format"; echo "<br />";
echo filter_var('test@abc@abc.com', FILTER_VALIDATE_EMAIL) ? "Valid email format": "Invalid email format"; echo "<br />";
echo filter_var('test@abc..com', FILTER_VALIDATE_EMAIL) ? "Valid email format": "Invalid email format"; echo "<br />";
echo filter_var('http://abc.com', FILTER_VALIDATE_EMAIL) ? "Valid email format": "Invalid email format"; echo "<br />";
echo filter_var('http://test@yahoo.com', FILTER_VALIDATE_EMAIL) ? "Valid email format": "Invalid email format"; echo "<br />";
?>

[wpdm_file id=45]

Output:
Valid email format
Valid email format
Invalid email format
Invalid email format
Invalid email format
Invalid email format
Invalid email format

Line 2 It is a valid formatted email address
Line 3 It is also a valid formatted email address. There might have dot before the @ sign
Line 4 This is invalid formatted email address as there is no dot in the host name after @ sign
Line 5 This is invalid formatted email address as there is double @ sign
Line 6 This is invalid formatted email address as there is two consecutive dots in the host name
Line 7 This is invalid formatted email address as there is http:// and no @ sign
Line 8 This is invalid formatted email address because of the http:// part.

Note: To use this method, your PHP version must be PHP 5.2.0 or better