【问题标题】:Email address validation in php (other than filter_var)php 中的电子邮件地址验证(filter_var 除外)
【发布时间】:2017-04-11 14:33:19
【问题描述】:

嘿,这是我关于电子邮件地址过滤的第二个问题,但我真的很偏执,我不喜欢人们仍然可以“绕过”php 中的默认电子邮件地址验证这一事实。

一个例子:

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

如果您想知道,这会显示“有效的电子邮件!”。

有没有办法阻止它?我希望人们只能使用传统的电子邮件地址 (name@domain.ltd) 进行注册。一个复杂的正则表达式?图书馆?我似乎找不到解决方案。

再次感谢。

【问题讨论】:

    标签: php regex validation email filtering


    【解决方案1】:

    这是一个有效的电子邮件地址。所以......我没有看到问题。但是你可以做这样的事情(当然,这在一个函数中利用了所有的过滤方法,所以你可以缩短一点):

    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;
        }
    }
    

    【讨论】:

    • 是的,根据标准,我知道这是一个有效的电子邮件地址,但没有人使用 IP 地址而不是域,还有许多其他有效但奇怪的电子邮件通过过滤器的示例。我去看看你包含的功能,谢谢!
    • @Hector 特别是checkdnsrr 看看。
    • "nobody" 有点明确。为 IP 设置电子邮件是完全有效的,尽管并不常见 - 但是,这是一种不太明显的电子邮件的方法 - 在 IP 上设置电子邮件服务器,并且只要该 IP 没有专门注册,例如,跟踪它变得不那么容易了(没有欺骗任何东西)。
    • @Hector,接受“有效但奇怪的电子邮件”有什么问题?如果它们是有效的,它们就是有效的。限制超出标准范围的电子邮件是不负责任的。这比说“我的用户只能拥有 Gmail 地址。任何使用任何其他域的人都不走运。”
    猜你喜欢
    • 2015-12-08
    • 2011-04-19
    • 2014-06-12
    • 1970-01-01
    • 2013-11-12
    • 2016-06-20
    • 2011-05-28
    • 1970-01-01
    相关资源
    最近更新 更多