如何在 PHP 中验证电子邮件?

发布于 2024-11-04 17:11:59 字数 344 浏览 3 评论 0原文

如何使用 php5 验证输入值是有效的电子邮件地址。现在我正在使用此代码

function isValidEmail($email){ 
     $pattern = "^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$"; 

     if (eregi($pattern, $email)){ 
        return true; 
     } 
     else { 
        return false; 
     }    
} 

,但它显示已弃用的错误。我该如何解决这个问题。请帮我。

How can I validate the input value is a valid email address using php5. Now I am using this code

function isValidEmail($email){ 
     $pattern = "^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$"; 

     if (eregi($pattern, $email)){ 
        return true; 
     } 
     else { 
        return false; 
     }    
} 

but it shows deprecated error. How can I fix this issue. Please help me.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

我纯我任性 2024-11-11 17:12:00

您可以使用 filter_var() 函数,它为您提供了许多方便的验证和清理选项。

filter_var($email, FILTER_VALIDATE_EMAIL)

如果您不想更改依赖于您的函数的代码,只需执行以下操作:

function isValidEmail($email){ 
    return filter_var($email, FILTER_VALIDATE_EMAIL) !== false;
}

注意< /strong>:对于其他用途(需要正则表达式的地方),已弃用的 ereg 函数系列(POSIX Regex 函数)应替换为 preg 系列(PCRE 正则表达式函数)。存在少量差异,阅读手册就足够了。

更新1:正如所指出的@binaryLV

PHP 5.3.3 和 5.2.14 有一个与以下相关的 bug
FILTER_VALIDATE_EMAIL,验证时导致段错误
大值。简单而安全的解决方法是使用 strlen()
filter_var() 之前。我不确定 5.3.4 Final,但它是
写道一些 5.3.4-snapshot 版本也受到影响。

此错误已被修复。

更新 2:此方法当然会将 bazmega@kapa 验证为有效的电子邮件地址,因为事实上它是一个有效的电子邮件地址。但大多数时候在互联网上,您还希望电子邮件地址具有 TLD:[电子邮件受保护]。正如这篇博客文章中所建议的(链接由@Istiaque Ahmed),您可以增强 filter_var () ,使用正则表达式检查域部分中是否存在点(但不会检查有效 TLD):

function isValidEmail($email) {
    return filter_var($email, FILTER_VALIDATE_EMAIL) 
        && preg_match('/@.+\./', $email);
}

@Eliseo Ocampos 指出,这个问题只存在于 PHP 5.3 之前,其中版本中他们更改了正则表达式,现在它执行此检查,因此您不必这样做。

You can use the filter_var() function, which gives you a lot of handy validation and sanitization options.

filter_var($email, FILTER_VALIDATE_EMAIL)

If you don't want to change your code that relied on your function, just do:

function isValidEmail($email){ 
    return filter_var($email, FILTER_VALIDATE_EMAIL) !== false;
}

Note: For other uses (where you need Regex), the deprecated ereg function family (POSIX Regex Functions) should be replaced by the preg family (PCRE Regex Functions). There are a small amount of differences, reading the Manual should suffice.

Update 1: As pointed out by @binaryLV:

PHP 5.3.3 and 5.2.14 had a bug related to
FILTER_VALIDATE_EMAIL, which resulted in segfault when validating
large values. Simple and safe workaround for this is using strlen()
before filter_var(). I'm not sure about 5.3.4 final, but it is
written that some 5.3.4-snapshot versions also were affected.

This bug has already been fixed.

Update 2: This method will of course validate bazmega@kapa as a valid email address, because in fact it is a valid email address. But most of the time on the Internet, you also want the email address to have a TLD: [email protected]. As suggested in this blog post (link posted by @Istiaque Ahmed), you can augment filter_var() with a regex that will check for the existence of a dot in the domain part (will not check for a valid TLD though):

function isValidEmail($email) {
    return filter_var($email, FILTER_VALIDATE_EMAIL) 
        && preg_match('/@.+\./', $email);
}

As @Eliseo Ocampos pointed out, this problem only exists before PHP 5.3, in that version they changed the regex and now it does this check, so you do not have to.

亚希 2024-11-11 17:12:00

请参阅 http://www.php.net/manual/en/function 处的注释.ereg.php

<前><代码>注意:

从 PHP 5.3.0 开始,正则表达式扩展已被弃用,取而代之的是
PCRE 扩展。调用这个
函数将发出 E_DEPRECATED
注意。请参阅差异列表
获取有关转换为 PCRE 的帮助。

<前><代码>注意:

preg_match(),它使用与 Perl 兼容的正则表达式
语法,通常是更快的替代方案
到 ereg()。

See the notes at http://www.php.net/manual/en/function.ereg.php:

Note:

As of PHP 5.3.0, the regex extension is deprecated in favor of
the PCRE extension. Calling this
function will issue an E_DEPRECATED
notice. See the list of differences
for help on converting to PCRE.

Note:

preg_match(), which uses a Perl-compatible regular expression
syntax, is often a faster alternative
to ereg().

刘备忘录 2024-11-11 17:12:00

这是旧帖子,但我将分享一个我的解决方案,因为之前没有人在这里提到一个问题。

新的电子邮件地址可以包含 UTF-8 字符或特殊域名,例如 .live.news 等。

我还发现某些电子邮件地址可以使用西里尔字母并且在所有情况下标准正则表达式或 filter_var() 将失败。

这就是为什么我为此制定了一个解决方案:

function valid_email($email) 
{
    if(is_array($email) || is_numeric($email) || is_bool($email) || is_float($email) || is_file($email) || is_dir($email) || is_int($email))
        return false;
    else
    {
        $email=trim(strtolower($email));
        if(filter_var($email, FILTER_VALIDATE_EMAIL)!==false) return $email;
        else
        {
            $pattern = '/^(?!(?:(?:\\x22?\\x5C[\\x00-\\x7E]\\x22?)|(?:\\x22?[^\\x5C\\x22]\\x22?)){255,})(?!(?:(?:\\x22?\\x5C[\\x00-\\x7E]\\x22?)|(?:\\x22?[^\\x5C\\x22]\\x22?)){65,}@)(?:(?:[\\x21\\x23-\\x27\\x2A\\x2B\\x2D\\x2F-\\x39\\x3D\\x3F\\x5E-\\x7E]+)|(?:\\x22(?:[\\x01-\\x08\\x0B\\x0C\\x0E-\\x1F\\x21\\x23-\\x5B\\x5D-\\x7F]|(?:\\x5C[\\x00-\\x7F]))*\\x22))(?:\\.(?:(?:[\\x21\\x23-\\x27\\x2A\\x2B\\x2D\\x2F-\\x39\\x3D\\x3F\\x5E-\\x7E]+)|(?:\\x22(?:[\\x01-\\x08\\x0B\\x0C\\x0E-\\x1F\\x21\\x23-\\x5B\\x5D-\\x7F]|(?:\\x5C[\\x00-\\x7F]))*\\x22)))*@(?:(?:(?!.*[^.]{64,})(?:(?:(?:xn--)?[a-z0-9]+(?:-+[a-z0-9]+)*\\.){1,126}){1,}(?:(?:[a-z][a-z0-9]*)|(?:(?:xn--)[a-z0-9]+))(?:-+[a-z0-9]+)*)|(?:\\[(?:(?:IPv6:(?:(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){7})|(?:(?!(?:.*[a-f0-9][:\\]]){7,})(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,5})?::(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,5})?)))|(?:(?:IPv6:(?:(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){5}:)|(?:(?!(?:.*[a-f0-9]:){5,})(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,3})?::(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,3}:)?)))?(?:(?:25[0-5])|(?:2[0-4][0-9])|(?:1[0-9]{2})|(?:[1-9]?[0-9]))(?:\\.(?:(?:25[0-5])|(?:2[0-4][0-9])|(?:1[0-9]{2})|(?:[1-9]?[0-9]))){3}))\\]))$/iD';
            return (preg_match($pattern, $email) === 1) ? $email : false;
        }
    }
}

此功能适用于所有案例和电子邮件格式。

This is old post but I will share one my solution because noone mention here one problem before.

New email address can contain UTF-8 characters or special domain names like .live, .news etc.

Also I find that some email address can be on Cyrilic and on all cases standard regex or filter_var() will fail.

That's why I made an solution for it:

function valid_email($email) 
{
    if(is_array($email) || is_numeric($email) || is_bool($email) || is_float($email) || is_file($email) || is_dir($email) || is_int($email))
        return false;
    else
    {
        $email=trim(strtolower($email));
        if(filter_var($email, FILTER_VALIDATE_EMAIL)!==false) return $email;
        else
        {
            $pattern = '/^(?!(?:(?:\\x22?\\x5C[\\x00-\\x7E]\\x22?)|(?:\\x22?[^\\x5C\\x22]\\x22?)){255,})(?!(?:(?:\\x22?\\x5C[\\x00-\\x7E]\\x22?)|(?:\\x22?[^\\x5C\\x22]\\x22?)){65,}@)(?:(?:[\\x21\\x23-\\x27\\x2A\\x2B\\x2D\\x2F-\\x39\\x3D\\x3F\\x5E-\\x7E]+)|(?:\\x22(?:[\\x01-\\x08\\x0B\\x0C\\x0E-\\x1F\\x21\\x23-\\x5B\\x5D-\\x7F]|(?:\\x5C[\\x00-\\x7F]))*\\x22))(?:\\.(?:(?:[\\x21\\x23-\\x27\\x2A\\x2B\\x2D\\x2F-\\x39\\x3D\\x3F\\x5E-\\x7E]+)|(?:\\x22(?:[\\x01-\\x08\\x0B\\x0C\\x0E-\\x1F\\x21\\x23-\\x5B\\x5D-\\x7F]|(?:\\x5C[\\x00-\\x7F]))*\\x22)))*@(?:(?:(?!.*[^.]{64,})(?:(?:(?:xn--)?[a-z0-9]+(?:-+[a-z0-9]+)*\\.){1,126}){1,}(?:(?:[a-z][a-z0-9]*)|(?:(?:xn--)[a-z0-9]+))(?:-+[a-z0-9]+)*)|(?:\\[(?:(?:IPv6:(?:(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){7})|(?:(?!(?:.*[a-f0-9][:\\]]){7,})(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,5})?::(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,5})?)))|(?:(?:IPv6:(?:(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){5}:)|(?:(?!(?:.*[a-f0-9]:){5,})(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,3})?::(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,3}:)?)))?(?:(?:25[0-5])|(?:2[0-4][0-9])|(?:1[0-9]{2})|(?:[1-9]?[0-9]))(?:\\.(?:(?:25[0-5])|(?:2[0-4][0-9])|(?:1[0-9]{2})|(?:[1-9]?[0-9]))){3}))\\]))$/iD';
            return (preg_match($pattern, $email) === 1) ? $email : false;
        }
    }
}

This function work perfectly for all cases and email formats.

嘦怹 2024-11-11 17:12:00

我总是用这个:

function validEmail($email){
    // First, we check that there's one @ symbol, and that the lengths are right
    if (!preg_match("/^[^@]{1,64}@[^@]{1,255}$/", $email)) {
        // Email invalid because wrong number of characters in one section, or wrong number of @ symbols.
        return false;
    }
    // Split it into sections to make life easier
    $email_array = explode("@", $email);
    $local_array = explode(".", $email_array[0]);
    for ($i = 0; $i < sizeof($local_array); $i++) {
        if (!preg_match("/^(([A-Za-z0-9!#$%&'*+\/=?^_`{|}~-][A-Za-z0-9!#$%&'*+\/=?^_`{|}~\.-]{0,63})|(\"[^(\\|\")]{0,62}\"))$/", $local_array[$i])) {
            return false;
        }
    }
    if (!preg_match("/^\[?[0-9\.]+\]?$/", $email_array[1])) { // Check if domain is IP. If not, it should be valid domain name
        $domain_array = explode(".", $email_array[1]);
        if (sizeof($domain_array) < 2) {
            return false; // Not enough parts to domain
        }
        for ($i = 0; $i < sizeof($domain_array); $i++) {
            if (!preg_match("/^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|([A-Za-z0-9]+))$/", $domain_array[$i])) {
                return false;
            }
        }
    }

    return true;
}

I always use this:

function validEmail($email){
    // First, we check that there's one @ symbol, and that the lengths are right
    if (!preg_match("/^[^@]{1,64}@[^@]{1,255}$/", $email)) {
        // Email invalid because wrong number of characters in one section, or wrong number of @ symbols.
        return false;
    }
    // Split it into sections to make life easier
    $email_array = explode("@", $email);
    $local_array = explode(".", $email_array[0]);
    for ($i = 0; $i < sizeof($local_array); $i++) {
        if (!preg_match("/^(([A-Za-z0-9!#$%&'*+\/=?^_`{|}~-][A-Za-z0-9!#$%&'*+\/=?^_`{|}~\.-]{0,63})|(\"[^(\\|\")]{0,62}\"))$/", $local_array[$i])) {
            return false;
        }
    }
    if (!preg_match("/^\[?[0-9\.]+\]?$/", $email_array[1])) { // Check if domain is IP. If not, it should be valid domain name
        $domain_array = explode(".", $email_array[1]);
        if (sizeof($domain_array) < 2) {
            return false; // Not enough parts to domain
        }
        for ($i = 0; $i < sizeof($domain_array); $i++) {
            if (!preg_match("/^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|([A-Za-z0-9]+))$/", $domain_array[$i])) {
                return false;
            }
        }
    }

    return true;
}
虫児飞 2024-11-11 17:12:00

用户数据对于一个优秀的开发者来说非常重要,所以不要再问了
再次对于相同的数据,使用一些逻辑来纠正数据中的一些基本错误。

验证电子邮件之前:首先,您必须删除电子邮件中的所有非法字符。

//This will Remove all illegal characters from email
$email = filter_var($email, FILTER_SANITIZE_EMAIL);

之后使用此 filter_var() 函数验证您的电子邮件地址。

filter_var($email, FILTER_VALIDATE_EMAIL)) // To Validate the email

例如

<?php
$email = "[email protected]";

// Remove all illegal characters from email
$email = filter_var($email, FILTER_SANITIZE_EMAIL);

// Validate email
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo $email." is a valid email address";
} else {
    echo $email." is not a valid email address";
}
?>

User data is very important for a good developer, so don't ask again
and again for same data, use some logic to correct some basic error in data.

Before validation of Email: First you have to remove all illegal characters from email.

//This will Remove all illegal characters from email
$email = filter_var($email, FILTER_SANITIZE_EMAIL);

after that validate your email address using this filter_var() function.

filter_var($email, FILTER_VALIDATE_EMAIL)) // To Validate the email

For e.g.

<?php
$email = "[email protected]";

// Remove all illegal characters from email
$email = filter_var($email, FILTER_SANITIZE_EMAIL);

// Validate email
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo $email." is a valid email address";
} else {
    echo $email." is not a valid email address";
}
?>
美胚控场 2024-11-11 17:12:00

使用:

var_dump(filter_var('[email protected]', FILTER_VALIDATE_EMAIL));
$validator = new EmailValidator();
$multipleValidations = new MultipleValidationWithAnd([
    new RFCValidation(),
    new DNSCheckValidation()
]);
$validator->isValid("[email protected]", $multipleValidations); //true

Use:

var_dump(filter_var('[email protected]', FILTER_VALIDATE_EMAIL));
$validator = new EmailValidator();
$multipleValidations = new MultipleValidationWithAnd([
    new RFCValidation(),
    new DNSCheckValidation()
]);
$validator->isValid("[email protected]", $multipleValidations); //true
把回忆走一遍 2024-11-11 17:12:00

请注意,地址为[电子邮件受保护] 是无效的,但 filter_var() 返回 true,许多其他字符串(电子邮件)使用 filter_var() 无效返回 true。

为了验证电子邮件,我使用此功能:

function correcorre($s){// correo correcto
    $x = '^([[:alnum:]](_|-|\.)*)*[[:alnum:]]+@([[:alnum:]]+(-|\.)+)*[[:alnum:]]+\.[[:alnum:]]+

请改进并分享,谢谢

; preg_match("!$x!i", $s, $M); if(!empty($M[0]))return($M[0]); }

请改进并分享,谢谢

take several care, a address as [email protected] is INVALID, but filter_var() return true, many others strings (emails) INVALIDS return true using filter_var().

for validate email I use this function:

function correcorre($s){// correo correcto
    $x = '^([[:alnum:]](_|-|\.)*)*[[:alnum:]]+@([[:alnum:]]+(-|\.)+)*[[:alnum:]]+\.[[:alnum:]]+

please improve and share, thanks

; preg_match("!$x!i", $s, $M); if(!empty($M[0]))return($M[0]); }

please improve and share, thanks

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文