How to Validate Email Address in PHP

On 6/17/2016

Hi there! Today's post is about validating email address in php. Yep! I know it's for novice and validating email-id is one of the primitive tasks for a developer to learn. Just in case you don't know, this is not about checking if an email address actually exists in real or not (that's entirely a different thing) but make sure it is well-formed and follows valid format. There is not one but several ways to make sure if an email address is valid and comply with the standard RFC format.

So How to Validate Email Address in PHP?

Here I'll show you two different methods to validate email address in php. The first method is by using filter_var() function and the second one by using regex pattern.

Method 1: Using filter_var() function

This is the absolute easiest way by which you can validate an email address in php. The method uses PHP's filter_var() function which is simple and safe to check if an email id is well formed and valid. The only downside to this method is it works only with PHP >= v5.2.0.

Below is the php function to validate email address using filter_var().

<?php
function validate_email($email=NULL) {
    return (filter_var($email, FILTER_VALIDATE_EMAIL) ? "$email is a valid email-id" : "$email is an invalid email-id");
}

echo validate_email("user.example@gmail.com");
echo "<br/>" . validate_email("user.example.com");

// output
// user.example@gmail.com is a valid email-id
// user.example.com is an invalid email-id
?>

Method 2: Using Mighty RegEx

If your PHP version is less than 5.2.0, then you have to go with the (crazy) regular expression method to validate the email address. Here is the php function to check if email-id is valid or not using regular expressions.

<?php
function validate_email($email=NULL) {
    return (preg_match("/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/",$email) ? "$email is a valid email-id" : "$email is an invalid email-id");
}

echo validate_email("user.example@gmail.com");
echo "<br/>" . validate_email("user_example@yahoo");

// output
// user.example@gmail.com is a valid email-id
// user_example@yahoo is an invalid email-id
?>

By using the above two methods you can easily validate the email address in php but still using filter_var() is the best option in most of the cases.

Also Read: Get Web Page Title and Meta Description from URL in PHP

I hope you find this tutorial useful! Please let me know your queries through comments.

1 comment:

  1. Great post ! To make successful email address there is need to verify email address. Your technique is useful to validate email address in php. Get best features to verify & check email list address by Email Validation services.

    ReplyDelete

Contact Form

Name

Email *

Message *