简体   繁体   English

PHP电子邮件表单验证不

[英]PHP email form validating doesn

I'm kinda new in PHP and I've created a form that should validate data and submit an error if any field is blank or incorrect.我是 PHP 新手,我创建了一个表单,该表单应该验证数据并在任何字段为空或不正确时提交错误。 It doesn't tho.它没有。 Even if email is wrong or any field is empty and the errors are shown it still sends an email.即使电子邮件错误或任何字段为空并显示错误,它仍会发送电子邮件。 And the headers are not showing in the message.并且消息中没有显示标题。 The only case when the errors are shown and the mail isn't send is the case when all fields are empty.显示错误且未发送邮件的唯一情况是所有字段都为空的情况。 Here's the code:这是代码:

<?php
$NameErr = $EmailErr = $SubErr = $MessErr = "";
$Name = $Email = $Subject = $Message = "";
$header = "From: " . $Email . "Name: " . $Name . "\r\n";
$header .= "Content-Type: text/plain";
$To = "xxx@gmail.com";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if (empty($_POST["Name"])) {
        $NameErr = "Name is required";
    } else {
        $Name = test_input($_POST["Name"]);
        if (!preg_match("/^[a-zA-Z ]*$/", $Name)) {
            $NameErr = "Only letters and white space allowed!";
        }
    }
    if (empty($_POST["Email"])) {
        $EmailErr = "Email is required";
    } else {
        $Email = test_input($_POST["Email"]);
        if (!filter_var($Email, FILTER_VALIDATE_EMAIL)) {
            $EmailErr = "Invalid email format";
        }
    }
    if (empty($_POST["Subject"])) {
        $SubErr = "Subject is required";
    } else {
        $Subject = test_input($_POST["Subject"]);
    }
    if (empty($_POST["Message"])) {
        $MessErr = "Message is required";
    } else {
        $Message = test_input($_POST["Message"]);
    }
}

function test_input($data) {
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;
}
?>

<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
    <p><input class="w3-input w3-padding-16" type="text" placeholder="Name" name="Name"></p>
    <span class="error"> <?php echo $NameErr; ?></span>
    <p><input class="w3-input w3-padding-16" type="text" placeholder="Email" name="Email"></p>
    <span class="error"> <?php echo $EmailErr; ?></span>
    <p><input class="w3-input w3-padding-16" type="text" placeholder="Subject" name="Subject"></p>
    <span class="error"> <?php echo $SubErr; ?></span>
    <p><input class="w3-input w3-padding-16" type="text" placeholder="Message" name="Message"></p>
    <span class="error"> <?php echo $MessErr; ?></span>
    <p>
        <button class="w3-btn w3-grey w3-padding-large w3-hover-green" type="submit" value="Submit" name="pressed">
            <i class="fa fa-paper-plane"></i> SEND MESSAGE
        </button>
    </p>
</form>
<?php
if (isset($_POST["pressed"])) {
    if (empty($NameErr && $SubErr && $MessErr && $EmailErr)) {
        mail($To, $Subject, $Message, $header);
        echo "Email sent.";
    } else {
        echo "Error.";
    }
}
?> 

Can you help me?你能帮助我吗? Error validating is on and it doesn't show me any errors.错误验证已开启,它没有显示任何错误。

use isset function instead of empty() to check if the field is posted or not.使用isset函数而不是empty()来检查该字段是否已发布。 example:例子:

if (!isset($_POST["Name"])) {
...

also there is no need to check the request method, $_POST will only catch post requests.也不需要检查请求方法, $_ POST 只会捕获 post 请求。

The way you're constructing your empty check towards the bottom is incorrect:您在底部构造empty支票的方式不正确:

if (empty($NameErr && $SubErr && $MessErr && $EmailErr)){

The only way that this will evaluate to false is if all of the error messages are set, and the above snippet will break before PHP 5.5 (as Felippe mentioned in the comments).这将评估为false的唯一方法是如果所有错误消息都已设置,并且上面的代码段将在 PHP 5.5 之前中断(如 Felippe 在评论中提到的)。 What you want instead is the below;你想要的是下面的; it returns true only if none of the error messages are set:仅当未设置任何错误消息时才返回true

if (empty($NameErr)
   && empty($SubErr)
   && empty($MessErr)
   && empty($EmailErr)) {

Another way to do this would be to另一种方法是

  • extract the validation logic into methods for readability,将验证逻辑提取到方法中以提高可读性,
  • read off of an $errors array instead of $NameErr , $SubjectErr , etc.读取$errors数组而不是$NameErr$SubjectErr等。
  • keep POST logic together (instead of split between the beginning and end)将 POST 逻辑保持在一起(而不是在开始和结束之间拆分)

To those ends, I've rewritten your snippet below:为此,我在下面重写了您的代码段:

<?php
function validateName($input)
{
    if (empty($input)) {
        return 'Name is required';
    }
    if (preg_match("/^[a-zA-Z ]*$/", $input) != 1) {
        return 'Name may only contain letters and spaces';
    }
    return null;
}

function validateEmail($input)
{
    if (empty($input)) {
        return 'Email is required';
    }
    if (filter_var($input, FILTER_VALIDATE_EMAIL)) {
        return 'Email is in an invalid format';
    }
    return null;
}

function validateSubject($input)
{
    return empty($input) ? 'Subject is required' : null;
}

function validateMessage($input)
{
    return empty($input) ? 'Message is required' : null;
}

function test_input($data)
{
    return htmlspecialchars(stripslashes(trim($data)));
}

$errors = [];
$notification = '';

if ($_SERVER["REQUEST_METHOD"] == "POST") {

    $name = test_input($_POST['name'] ?: '');
    $email = test_input($_POST['email'] ?: '');
    $subject = test_input($_POST['subject'] ?: '');
    $message = test_input($_POST['message'] ?: '');

    if (($error = validateName($name)) !== null) {
        $errors['name'] = $error;
    }
    if (($error = validateEmail($email)) !== null) {
        $errors['email'] = $error;
    }
    if (($error = validateSubject($subject)) !== null) {
        $errors['subject'] = $error;
    }
    if (($error = validateMessage($message)) !== null) {
        $errors['message'] = $error;
    }

    if (empty($errors)) {
        $headers = [
            "From: $name <$email>",
            "Content-Type: text/plain",
        ];
        $to = "xxx@gmail.com";

        mail($to, $subject, $message, implode("\r\n", $headers));
        $notification = 'The email was sent!';
    } else {
        $notification = 'The email could not be sent; please check below for errors.';
    }
}

?>
<form method="post" action="<?= htmlspecialchars($_SERVER['PHP_SELF']) ?>">
    <?php if (!empty($notification)): ?><p><?= $notification ?></p><?php endif; ?>

    <p><input class="w3-input w3-padding-16" type="text" placeholder="Name" name="name" required></p>
    <?php if (isset($errors['name'])): ?><span class="error"> <?= $errors['name'] ?></span><?php endif; ?>

    <p><input class="w3-input w3-padding-16" type="email" placeholder="Email" name="email" required></p>
    <?php if (isset($errors['email'])): ?><span class="error"> <?= $errors['email'] ?></span><?php endif; ?>

    <p><input class="w3-input w3-padding-16" type="text" placeholder="Subject" name="subject" required></p>
    <?php if (isset($errors['subject'])): ?><span class="error"> <?= $errors['subject'] ?></span><?php endif; ?>

    <p><input class="w3-input w3-padding-16" type="text" placeholder="Message" name="message" required></p>
    <?php if (isset($errors['message'])): ?><span class="error"> <?= $errors['message'] ?></span><?php endif; ?>

    <p>
        <button class="w3-btn w3-grey w3-padding-large w3-hover-green" type="submit">
            <i class="fa fa-paper-plane"></i> SEND MESSAGE
        </button>
    </p>
</form>

So I've re designed the code structure for you.所以我为你重新设计了代码结构。 Generally calling a class and a function will keep your files and your code cleaner.通常调用一个类和一个函数会让你的文件和代码更干净。

So with this being said, let me show you some insight.因此,话虽如此,让我向您展示一些见解。 This is where your form will be located for example: form.php这是您的表单所在的位置,例如:form.php

<?php

require ('mail.php');

$send = new Mail();

if (isset($_POST['sendIt']))
{
    $send->sendMail($_POST['nameP'], $_POST['email'], $_POST['subject'], $_POST['message']); // Call the class and function
}

?>


<form id="contact" method="post">
    <div class="container">
        <input type="text" name="nameP" placeholder="Name *" /><br />
        <input  type="email" name="email" placeholder="Email *"/><br />
        <input type="text" name="subject" placeholder="Subject *"><br />
        <textarea name="message" id="" cols="30" rows="10"></textarea>
        <input type="submit" name="sendIt" id="submit">
    </div>
</form>

Then create yourself a mail.php file to store the class and the functions revolving around mailing in general:然后为自己创建一个 mail.php 文件来存储类和一般围绕邮件发送的功能:

<?php

class Mail
{
    public function sendMail($name, $email, $subject, $message)
    {
        if (!empty($name))
        {
            if (!empty($email))
            {
                if (!empty($subject))
                {
                    if (!empty($message))
                    {
                                $email_to = 'Your@emailAddress';
                                $header = 'From: ' . $name ."<noreply@youremail>". "\r\n" .
                                    'Reply-To: ' . $email . "\r\n" .
                                    'X-Mailer: PHP/' . phpversion();

                                @mail($email_to, 'Enquiry Received', 'Name: ' . $name . "\r\n\r\n". 'Email Address: ' .$email."\r\n\r\n" . 'Message: ' .$message."\r\n\r\n". $header);

                                echo "SUCCESS MESSAGE";
                    } else {
                        echo "Please fill in your message";
                    }
                } else {
                    echo "Please provide a subject.";
                }
            } else {
                echo "Please provide your email address.";
            }
        } else {
            echo "Please provide your name.";
        }

    }
}
?>

This will generally clear the form if there is an error by default however you can then simply add value="<?php echo $_POST['whateverThisFormIsFor'];?>如果默认情况下出现错误,这通常会清除表单,但是您可以简单地添加value="<?php echo $_POST['whateverThisFormIsFor'];?>

I hope this will help and give you some further insight.我希望这会有所帮助,并为您提供一些进一步的见解。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM