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


How to validate an email address with php?

我开始尝试编写一个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>';}
?>

像这样:

$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>';
}    

理想情况下,您还应该检查是否定义了$_POST['mail'],因为根据您的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>';
}