自我提交PHP表单验证

时间:2018-01-06 05:43:43

标签: php html forms contact-form

我已经将PHP表单提交给self并进行错误验证,但表单未提交。我们的想法是,当用户点击提交按钮并且没有填写他们输入的所有必填字段或电子邮件地址时存在缺陷,然后通过添加按CSS排序的错误类来发生错误。 CSS很好,但表单没有提交。我很感激你的帮助。

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Email</title>
    </head>
    <body>
    <?php
        $error = '';
        $to = "name@example.com";

        if ($_SERVER["REQUEST_METHOD"] == "POST") {
            if (empty($_POST["name"]) || empty($_POST["email"]) || empty($_POST["message"])) {
                $error = 'class="error" ';
            } else {
                $name = stripslashes(trim($_POST["name"]));
                $email = stripslashes(trim($_POST["email"]));
                $message = stripslashes(trim($_POST["message"]));
                $pattern = '/[\r\n]|Content-Type:|Bcc:|Cc:/i';

                if (preg_match($pattern, $name) || preg_match($pattern, $email)) {
                    $error = 'class="error" ';
                }

                $emailIsValid = filter_var($email, FILTER_VALIDATE_EMAIL);

                if ($name && $email && $emailIsValid && $message) {
                    $subject = "From $name";
                    $body = "Name: $name <br /> Email: $email <br /> Message: $message";

                    $headers = "Reply-To: $email";

                    $success = mail($to, $subject, $body, $headers);
                    if ($success) {
                        header("Location: /email/sent/");
                    } else {
                        header("Location: /error/");
                    }
                }
            }
        }
        ?>

        <form method="post" action="<?php echo htmlspecialchars($_SERVER["REQUEST_URI"]); ?>">
            <input <?php echo $error; ?>type="text" name="name" placeholder="Full Name" spellcheck="false">
            <input <?php echo $error; ?>type="text" email="email" placeholder="Email Address" spellcheck="false">
            <textarea <?php echo $error; ?>type="text" message="message" placeholder="Message" rows="6" spellcheck="false"></textarea>
            <button type="submit" name="submitted">submit</button>
        </form>
    </body>
</html>

1 个答案:

答案 0 :(得分:1)

注意:您的表单标签中存在拼写错误。您在双引号内使用双引号。

使用此内容

<form method="post" action="<?php echo htmlspecialchars($_SERVER["REQUEST_URI"]); ?>">
and
if ($_SERVER["REQUEST_METHOD"] == "POST") {

使用

<form method="post" action="<?= $_SERVER['PHP_SELF'] ?>">
and
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['submitbutton'])) {
//SO IT WILL PERFORM ONLY WHEN SUBMIT BUTTON WAS PRESSED

了解更多您可以了解here

Live Demo 可用