ProAnswers.org

Is it possible to validate an email in PHP?

Is it possible to validate an email in PHP?

The PHP filter “validate_email” provides an easy, simple way to determine if a string is an email or not.

You’ll want to use the filter with a function such as filter_var(). For example:

$email = "someone@example.com";

$filterResult = filter_var($email, FILTER_VALIDATE_EMAIL)

if ($filterResult)

{ echo "E-mail is valid!"; }

else

{ echo "E-mail is not valid!"; }

There are alternatives to using the PHP filter, if you would like to be completely sure about what you’re checking - and know how it’s checked. A longer, laid out example:

function checkmail($mail)

{

    $mReturn = FALSE;

// Get the host / domain information of the address (and validate its existence)

    $email_host = explode("@", $mail);
    $email_host = $email_host['1'];
    $email_resolved = gethostbyname($email_host);

// Check the syntax of the address

    if ($email_resolved != $email_host && eregi("^[0-9a-z]([-_.~]?[0-9a-z])*@[0-9a-z]([-.]?[0-9a-z])*\\.[a-z]{2,4}$",$mail))

        {
        $mReturn = TRUE;
        }

// Return whether the domain exists, and the E-mail is valid (TRUE or FALSE)

    return $mReturn;

}

$mail = example@example.com;

$result = checkMail($mail);

if ($result)

{
echo "E-mail is valid!";
}

else

{
echo "E-mail is not valid!";
}

After you have validated if the URL of the address is valid, you should actually check whether it exists. There is no way to check if an E-mail was sent properly in PHP as of yet - however, you can send an E-mail with an “activation link” in it to properly identify if the E-mail is working and exists.

The activation link should lead to an activation page, which checks GET variables (propagated in the URL), and then checks if those variables are equal to the real activation code - saved on your server (or otherwise).