Hector
Hector

Reputation: 1

Email address validation in php (other than filter_var)

Hey it's my second question regarding email address filtering but I am really paranoid and I don't like the fact people can still "bypass" the default email address validation in php.

An example:

$i = "email@[1.1.1.1]";
if (!filter_var($i, FILTER_VALIDATE_EMAIL)) {
$msg = "Invalid email address"; 
} else { echo "valid email!"; }

This echos "valid email!", if you were wondering.

Is there a solution that prevents it? I want people to be able to register only using conventional email addresses ([email protected]). A complex regex? a library? I can't seem to find a solution.

Thanks again.

Upvotes: 0

Views: 459

Answers (1)

junkfoodjunkie
junkfoodjunkie

Reputation: 3178

That IS a valid email-address. So... I don't see the problem. But you can do something like this (granted, this utilizes all of the filter-methods in one function, so you can shorten it a bit):

function filtervariable($string,$type,$method) {
    //function for sanitizing variables using PHPs built-in filter methods
    $validEmail = false;

    if ($method == 'sanitize') {
        $filtermethod = 'FILTER_SANITIZE_';
    } elseif ($method == 'validate') {
        $filtermethod = 'FILTER_VALIDATE_';
    } else {
        return;
    }
    switch ($type) {
        case 'email':
        case 'string':
        case 'number_int':
        case 'int':
        case 'special_chars':
        case 'url':
        $filtertype = $filtermethod.strtoupper($type);
        break;
    }

    if ($filtertype == 'FILTER_VALIDATE_EMAIL' && !empty($string)) {
        list($local,$domain) = explode('@',$string);

        $localLength = strlen($local);
        $domainLength = strlen($domain);

        $checkLocal = explode('.',$domain);

        if (($localLength > 0 && $localLength < 65) && ($domainLength > 3 && $domainLength < 256) && (checkdnsrr($domain,'MX') || checkdnsrr($domain,'A') || ($checkLocal[1] == 'loc' || $checkLocal[1] == 'dev' || $checkLocal[1] == 'srv'))) { // check for "loc, dev, srv" added to cater for specific problems with local setups
            $validEmail = true;
        } else {
            $validEmail = false;
        }
    }
    if (($filtertype == 'FILTER_VALIDATE_EMAIL' && $validEmail) || $filtertype != 'FILTER_VALIDATE_EMAIL') {
        return filter_var($string, constant($filtertype));
    } else {
        return false;
    }
}

Upvotes: 1

Related Questions