Php电子邮件表单验证,验证无效

时间:2016-07-04 17:03:42

标签: php

您好,这可能是一个愚蠢的问题,但我是一个PHP的初学者,并希望制作一个验证的电子邮件表单,当我点击按钮提交它重新加载页面发送邮件,即使并非所有的输入都完成点击按钮后,表示没有任何表格已完成。我是否需要ajax才能让这种情况发生? 以下是您可能更了解的代码: 腓:

<?php  
$nameErr = $emailErr = $messageErr = "";

$to = 'example@example.com';
$subject = 'Email form test';

$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if (isset($_POST["name"] )) {
        $nameErr = "* Please enter your name";
    } else {
        $name = test_input($_POST["name"]);
    }

    if (isset($_POST["email"])) {
        $emailErr = "* Please enter your email"; 
    } else {
        $email = test_input($_POST["email"]);
    }

    if (isset($_POST['message'])) {
        $messageErr = "* Please enter a message"; 
    } else {
        $message = test_input($_POST["message"]);
    }  

$message = <<<EMAIL

$name
$email
$message

EMAIL;

$header = '$email';

if ($_POST['submit']){
mail( $to , $subject , $message , $header );
$feedback = 'Your email has been sent.';
}
}

?>

HTML:

    <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
     <div class="name">
        <input type="text" name="name" id="name" value="" placeholder="Name" size="50">
        <span class="error"><?php echo $nameErr;?></span>
    </div>
<br>
    <div class="email">
        <input type="text" name="email" id="email" value="" placeholder="E-Mail" size="50">
        <span class="error"><?php echo $emailErr;?></span>
    </div>
<br>
    <div class="message">
        <textarea name="message" id="message" placeholder="Enter your message" rows="6"></textarea>
        <span class="error"><?php echo $messageErr;?></span>
     </div>
<br>
    <div class="submit">
       <input type="submit" name="submit" class="button special">
    </div>
</form>    
<p id="feedback"><?php echo $feedback; ?></p>

谢谢。

2 个答案:

答案 0 :(得分:1)

我稍微重写了你的代码,我认为它应该像这样工作。

<?php  

$errors = array();
$to = 'example@example.com';
$subject = 'Email form test';

$requiredFields = array('name', 'email', 'message');

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    foreach ($required as $field) {
        if (!array_key_exists($field, $_POST)) {
             $errors[$field] = '* '.$field.' cannot be empty';
        } else if (!test_input($_POST[$field])) {
             $errors[$field] = '* '.$field.' does not meet the validation';
        }
    }

    $message = $name."\n".$email."\n".$message."\n";
    $header = '$email';
    if (isset($_POST['submit'])) {
        mail( $to , $subject , $message , $header);
    }
    $feedback = 'Your email has been sent.';
}
?>

答案 1 :(得分:0)

请参阅isset手册。它确定是否设置了变量并且不是NULL。

//Pay attention to ! (negation)
if (!isset($_POST["email"])) {
    $emailErr = "* Please enter your email"; 
}

验证您可以使用的电子邮件:

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