2016-06-07 149 views
-1

我做了一個表單,人們可以輸入他們的電子郵件。 問題是他們現在可以在該字段中添加他們想要的所有內容,我希望他們只能輸入有效的電子郵件。我在互聯網上找到了這段代碼。電子郵件驗證不起作用

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { 
    $emailErr = "Invalid email format"; 
} 

並實現了它在我的PHP郵件發送代碼:

<?php 

$email = $_POST['subscribefield']; 

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { 
    $emailErr = "Invalid email format"; 
} 


$to = "[email protected]"; 
$subject = "Abonee voor de nieuwsbrief"; 
$body = "$email \n Heeft zich aangemeld voor de nieuwsbrief"; 

mail($to, $subject, $body); 

echo "your mail was sent"; 
?> 

還不行。我做錯了什麼?

由於提前,

凱文

+0

你是什麼意思_ 「還不行」 _?什麼不行?您使用的輸入是什麼?預期的結果是什麼? – 1615903

+0

我基本上輸入了類似「lalala」的東西,但它仍然發送:x @ 1615903 – Kevin

+1

您的代碼中的任何地方都沒有使用'$ email'或'$ emailErr'變量。你總是發送到'test @ hotmail.com'。 – 1615903

回答

1

您不必if語句的任何地方,將檢查$ emailErr。 如:

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { 
    $emailErr = "Invalid email format"; 
} 

if(isset($emailErr) === FALSE) 
{ 
    $to = "[email protected]"; 
    $subject = "Abonee voor de nieuwsbrief"; 
    $body = "$email \n Heeft zich aangemeld voor de nieuwsbrief"; 

    mail($to, $subject, $body); 

    echo "your mail was sent"; 
} 

或者乾脆

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { 
    echo "Invalid email format"; 
    die(); 
} 
1

你不輸出錯誤。 嘗試是這樣的:

if (filter_var('[email protected]', FILTER_VALIDATE_EMAIL)) { 
     echo 'VALID'; 
    //Do you email send stuff 

    } else { 
     echo 'NOT VALID'; 
    //Display the error and don't send the mail 
    } 
2

你不應該嘗試發送,如果電子郵件地址是錯誤的。

$email = $_POST['subscribefield']; 

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) 
    { 
    $emailErr = "Invalid email format"; 
    } 
    else 
    { 
    $to = "[email protected]"; 
    $subject = "Abonee voor de nieuwsbrief"; 
    $body = "$email \n Heeft zich aangemeld voor de nieuwsbrief"; 
    mail($to, $subject, $body); 
    echo "your mail was sent"; 
    } 

?>