2014-02-12 51 views
0

我有一些if語句驗證提交給我的表單的電子郵件地址。然而,即使並非滿足以下所有條件,表格也會提交。它似乎尊重的是filter_var條件。爲什麼會這樣做?失敗的驗證是最後一條說明電子郵件無法訪問的聲明。它表示電子郵件地址無法訪問。但它反正通過電子郵件提交表格。 $擦洗是一個功能我在表單中使用,以從可能的垃圾郵件儘管有錯誤提交電子郵件驗證表格

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

} 
+0

驗證失敗,什麼是$ scrubbed? –

+1

直到表單提交後才運行PHP驗證。如果你想阻止提交的表單,你需要在客戶端驗證它 – Anigel

+0

失敗的驗證是最後一條說明電子郵件無法訪問的if語句。它表示電子郵件地址無法訪問。但它反正通過電子郵件提交表格。 $ scrubbed是我在表單中用來清除可能的垃圾郵件中的表單域的函數。 – user3286022

回答

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> 

請注意,這只是一些代碼,用於說明目的,無關與適當的軟件設計,可重用性,...好東西就是好軟件的一部分。