如何使用 php 验证电子邮件地址? [复制]

Posted

技术标签:

【中文标题】如何使用 php 验证电子邮件地址? [复制]【英文标题】:How to validate an email address with php? [duplicate] 【发布时间】:2014-06-07 11:53:54 【问题描述】:

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

?>

【问题讨论】:

那么可能是重复的:) 查看***.com/questions/201323/…并决定发送确认电子邮件进行验证 不要使用正则表达式。使用这个:***.com/a/12026873/362536 【参考方案1】:

像这样:

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

【讨论】:

我不知道为什么这被否决了。 也许其他人想要积分,请为正确答案投赞成票:) 根据票数,它没有被否决。 @Brad 那是我发表第一条评论的时候。否则,我不会这么说;-) @Fred-ii- 我相信你......只是指出来。也许有人快速或错误地投票。速射***!【参考方案2】:

理想情况下,您还应该检查 $_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>';

【讨论】:

您的建议是if ($mail == "" || !filter_var($mail, FILTER_VALIDATE_EMAIL)),但条件中不需要$mail == "" 好电话,我已经更新了代码以检查是否实际设置了 $_POST['mail']。

以上是关于如何使用 php 验证电子邮件地址? [复制]的主要内容,如果未能解决你的问题,请参考以下文章

如何在 PHP 中验证电子邮件?

如何使用 PHP 检查电子邮件地址是不是真实或有效

Symfony2 - 如何验证控制器中的电子邮件地址

当使用 PHP 在后端验证电子邮件时,如何将输入提交从禁用更改为启用?

Java 8/11+ 验证没有模式的电子邮件地址语法? [复制]

如何将验证错误从 php 返回到 swift 或 segue 成功