Best way to very email in PHP code

So verifing the email is most common problem for a web developer. how ever for this problem various solution is available like
  • Pattern in the input field
  • Input field type email
  • jQuery email:true
  • PHP : filter_var($email, FILTER_VALIDATE_EMAIL)
but still all these are fail to check the email with the dns check for which all of them tricked when you enter something like "gg.gg@com" valid mail but not working your origin may be. so here is the best possible solution in php you can apply for better implementation of email checking.

function validate_email($email) {
    if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $domain = explode("@", $email);
        $domain = end($domain); // Extract the domain
        // List of popular email domains
        $popularDomains = array("gmail.com", "yahoo.com", "outlook.com", "hotmail.com");
        if (checkdnsrr($domain, "MX")) {
            if (in_array($domain, $popularDomains)) {
                return true; // Valid email address with a popular domain
            } else {
                return false; // Valid email address, but not a popular domain
            }
        } else {
            return false; // Invalid domain
        }
    } else {
        return false; // Invalid email format
    }
}
?>

Calling part of the function


$emailToValidate = "bijay.to.access@gg.com";
if (validate_email($emailToValidate)) {
    echo "Valid email address";
} else {
    echo "Invalid email address for our requirement";
}
?>

 

Conclusion

Correct your coding and programming skills to achieve more.