电子邮件验证表单提交尽管有错误

时间:2014-02-12 17:15:43

标签: php validation email if-statement

我有一些if语句验证提交到我的表单的电子邮件地址。但是,即使并非所有if条件都满足,表单也会提交。它似乎尊重的是filter_var条件。它为什么要这样做?失败的验证是最后一个声明电子邮件无法访问的if语句。在表格上,它说电子邮件地址无法访问。但无论如何它通过电子邮件提交表格。 $ scrubbed是我在表单中用来清除可能的垃圾邮件中的表单字段的函数

    if (isset($scrubbed["email"])) {


    if (strlen($scrubbed["email"]) > 254) {
        echo "<p>The email address is too long: it must be 254 or less.</p>";
    }

    // Validate syntax with PHP.
    if ((($email = filter_var($scrubbed["email"], FILTER_VALIDATE_EMAIL)) === false)) {
        echo "<p>The email address has an invalid syntax.</p>";
    }

    // Validate DNS reachability.
    $host = substr($email, strrpos($email, "@") + 1) . ".";

    if (!checkdnsrr($host, "A") && !checkdnsrr($host, "AAAA") && !checkdnsrr($host, "MX")) {
        echo "<p>The email address is unreachable.</p>";
    }

}

1 个答案:

答案 0 :(得分:0)

如果您接受问题的答案,那就太好了。

$scrubbed["email"]只是空的,因此电子邮件始终无效。

让我们创建一个将提交给我们的简单表单。

<!doctype html>
<html>
<head>
    <title>Form</title>
</head>
<body>
<?php

/**
 * Validate submitted email address.
 *
 * @return null|string
 *   Returns <code>NULL</code> if the email address is valid, if the
 *   email address is invalid a string explaining the problem is returned.
 */
function validate_email() {
    $email = filter_input(INPUT_POST, "email", FILTER_VALIDATE_EMAIL);

    if ($email === false) {
        return "The email address has an invalid syntax.";
    }

    if (strlen($email) > 254) {
        return "The email address is too long: it must be 254 or less.";
    }

    $host = substr($email, strrpos($email, "@") + 1) . ".";
    if (!checkdnsrr($host, "A") && !checkdnsrr($host, "AAAA") && !checkdnsrr($host, "MX")) {
        return "The email address is unreachable.";
    }
}

// Check if we were called via POST.
if ($_SERVER["REQUEST_METHOD"] == "POST") {

    // Validate the email address and display the error message (if any).
    if (($error = validate_email())) {
        echo "<p>{$error}</p>";
    }
    // Otherwise let the user know that everything is okay.
    else {
        echo "<p>The email address is valid, not too long, and reachable.</p>";
    }

}

?>
    <form action="/" method="post" accept-charset="utf-8">
        <input type="email" name="email">
        <input type="submit">
    </form>
</body>
</html>

请注意,这只是用于说明目的的一些代码,与正确的软件设计,可重用性,......以及任何属于良好软件的任何内容无关。