PHP电子邮件表单验证

时间:2012-02-20 21:11:22

标签: php email validation

我正在为一个网站撰写评论表,并试图抵御垃圾邮件发送者。我从这个link获取了validEmail函数。

我在使用功能方面不是很有经验。这是调用该函数并验证用户电子邮件地址的正确方法吗?任何建议赞赏。谢谢

$email = $_POST['email'];

if (validEmail($email)) {

$to      = 'fsddfsdfa@gmail.com';
$subject = 'the subject';
$message = 'hello';
$headers = 'From: webmaster@example.com';

mail($to, $subject, $message, $headers);

print "Form submitted successfully: <br>Your name is <b>".$_POST['cname']."</b> and your email is <b>".$_POST['email']."</b><br>";

} else {

print "There was an error with your form submission.";

}

4 个答案:

答案 0 :(得分:3)

自5.2.0以来,PHP拥有自己的验证过滤器,可用于检查用户是否输入了正确的电子邮件地址。没有必要依赖于您在互联网上找到的东西,因为这些功能可能存在缺陷或损坏。要使用filter_var()进行电子邮件验证,解决方案将是:

if(!filter_var($email, FILTER_VALIDATE_EMAIL)){ 
    print "E-mail is correct";
} else {
    print "E-mail is not correct";
}

(另请注意,问题中的原始示例代码在其中一个打印件中缺少分号)。

答案 1 :(得分:1)

包含validEmail( $email );的函数应包含在您的文件中:

include "whatever.php"

(或者,您可以将该功能复制并粘贴到与您的代码相同的文件中)

您的if语句应如下所示:

if( validEmail( $email ) ) {
  // print your success message here
} else {
  // print your fail message here
}

在回答下面的评论时,你也可以这样写:

if( validEmail( $email ) === true ) {
  // print your success message here
} else {
  // print your fail message here
}

答案 2 :(得分:1)

整个链接的validEmail()函数可以替换为:

function validEmail($email)
{
    if (filter_var('bob@example.com', FILTER_VALIDATE_EMAIL) !== false) {
        $domain = preg_split("/@/", $email);
        $domain = $domain[count($domain) - 1];
        if (checkdnsrr($domain,"MX") || checkdnsrr($domain,"A")) {
            return true;
        }
    }
    return false;
}

虽然我只是从您链接的文章中获取checkdnsrr()功能。我不熟悉它,以前我还没有用它。内置的filter_var()函数可能就是您真正想要使用的功能,因为检查DNS需要时间(因此,每当有人向您的表单提交内容时,您的脚本可能会执行2次DNS查找)。

答案 3 :(得分:0)

if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo "e-Mail is Valid";
} else {
    echo "Invalid e-Mail";
}
相关问题