1

简单地说,我找到了这段代码来验证电子邮件:

filter_var($user_email, FILTER_VALIDATE_EMAIL)

但不幸的是,我不知道如何将其添加到从表单获取信息的 PHP 代码中:

<?php $name = $_POST['name'];
    $email = $_POST['email'];
    $message = $_POST['message'];
    $formcontent="From: $name \n Message: $message";
    $recipient = "example@example.com";
    $subject = "Contact Form";
    $mailheader = "From: $email \r\n";
    mail($recipient, $subject, $formcontent, $mailheader) or die("Error!");
?>

我使用 Ajax 来获取表单的提交信息。

4

4 回答 4

1

你可以使用filter_input函数。此函数将检查请求email中是否已发送参数,如果已发送POST,则将对其进行验证并返回经过验证的电子邮件或 FALSE。像这样做:

<?php 
    $email = filter_input( INPUT_POST, 'email', FILTER_VALIDATE_EMAIL );
    if ( $email ) {
        $name = $_POST['name'];
        $message = $_POST['message'];
        $formcontent="From: $name \n Message: $message";
        $recipient = "example@example.com";
        $subject = "Contact Form";
        $mailheader = "From: $email \r\n";
        mail($recipient, $subject, $formcontent, $mailheader) or die("Error!");
    } else {
        die("Email is ivalid!")
    }
?>
于 2013-09-14T21:59:45.270 回答
0
<?php 

    //if the form has been submitted
    if ( isset($_POST['submit']) ) {
        $name = $_POST['name'];
        $user_email = $_POST['email'];
        $message = $_POST['message'];

        //if user's email is not empty and is valid, send mail
        if ( !empty($user_email) && filter_var($user_email, FILTER_VALIDATE_EMAIL) ) {
            $formcontent="From: $name \n Message: $message";
            $recipient = $user_email;
            $subject = "Contact Form";
            $mailheader = "From: youremail@example.com \r\n";
            mail($recipient, $subject, $formcontent, $mailheader) or die("Error!");
        } else {
            //show error
            exit("Your email seems to be invalid.");
        }
    }

?>
于 2013-09-14T22:06:03.427 回答
0

You can use it like this:

<?php
    if(filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)){
        $email = $_POST['email'];
        $message = $_POST['message'];
        $formcontent="From: $name \n Message: $message";
        $recipient = "example@example.com";
        $subject = "Contact Form";
        $mailheader = "From: $email \r\n";
        mail($recipient, $subject, $formcontent, $mailheader) or die("Error!");

    } else {
        header("Location: your_form.html");

    }

If you're gonna insert this to a database it'll be good to sanitize your data with mysql_real_escape_string

Also display a good message when the email is wrong.

于 2013-09-14T21:56:38.603 回答
-1

如果你需要一个好的 PHP 函数来检查输入是否是一个有效的电子邮件地址,你可以使用这个:

function validateEmail($email) {
$e = false;
if ((trim ( $email )) == "") {
    $e = true;
} elseif (strlen ( $email ) > 40) {
    $e = true;
} elseif (! ((strpos ( $email, "." ) > 0) && (strpos ( $email, "@" ) > 0)) || preg_match ( "/[^a-zA-Z0-9.@_-]/", $email )) {
    $e = true;
}
return !$e;
}

如您所见,它将电子邮件长度限制为 40 个字符。

于 2013-09-14T22:04:37.933 回答