如何用php验证电子邮件地址?

时间:2014-04-22 21:53:11

标签: php validation email verification

我开始尝试编写一个php脚本来验证用户在我的表单中输入的电子邮件地址。 有人可以帮我完成吗?提前致谢。对你的帮助表示感谢 :) 注意:请不要告诉我使用javascript或jQuery。我需要用php:/

这样做
<?php
$mail = $_POST['mail'];
$formcontent = "Email: $mail";
$recipient = "email@example.com";
$subject = "Mail that uploaded picture";
$mailheader = "From: my website";

if ($mail == ""){
echo "Please enter a valid email address. We want to contact you using your email address. Do not worry, nobody will be able to see it.";
}

else{
mail($recipient, $subject, $formcontent, $mailheader) or die("Error!");
echo 'Your email address has been successfully added to your photo !<br>We will contact you later to tell you how to win the $50 000 :)<br><br>';}

?>

2 个答案:

答案 0 :(得分:2)

像这样:

$email = 'email@example.com';
if (filter_var($email, FILTER_VALIDATE_EMAIL)){
    echo 'Email OK';
}

在您的源代码中:

$mail = $_POST['mail'];
$formcontent = "Email: $mail";
$recipient = "email@example.com";
$subject = "Mail that uploaded picture";
$mailheader = "From: my website";

if (!filter_var($mail, FILTER_VALIDATE_EMAIL)){
    echo "Please enter a valid email address. We want to contact you using your email address. Do not worry, nobody will be able to see it.";
} else {
    mail($recipient, $subject, $formcontent, $mailheader) or die("Error!");
    echo 'Your email address has been successfully added to your photo !<br>We will contact you later to tell you how to win the $50 000 :)<br><br>';
}    

答案 1 :(得分:1)

理想情况下,您还应检查$ _POST [&#39; mail&#39;]是否已定义,因为您将收到错误/通知,具体取决于您的error_reporting级别和display_errors。

更新的代码:

if (!isset($_POST['mail']) || !filter_var($_POST['mail'], FILTER_VALIDATE_EMAIL)) {
    echo "Please enter a valid email address. We want to contact you using your email address. Do not worry, nobody will be able to see it.";
} else {
    $mail = $_POST['mail'];
    $formcontent = "Email: $mail";
    $recipient = "email@example.com";
    $subject = "Mail that uploaded picture";
    $mailheader = "From: my website";

    mail($recipient, $subject, $formcontent, $mailheader) or die("Error!");
    echo 'Your email address has been successfully added to your photo !<br>We will contact you later to tell you how to win the $50 000 :)<br><br>';
}