【问题标题】:Self Submit PHP Form Validation自行提交 PHP 表单验证
【发布时间】:2023-03-07 12:24:02
【问题描述】:

我已经制作了一个 PHP 表单以通过错误验证提交给自己,但该表单没有提交。这个想法是,当用户单击提交按钮并且没有填写所有必填字段或他们输入的电子邮件地址有缺陷时,通过添加按 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>

【问题讨论】:

  • 你这里有个错误:name="email" ..... type="text" email="email"
  • 这里有类似的错误:

标签: php html forms contact-form


【解决方案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可用

【讨论】:

  • 双引号内的双引号没有问题。 php变量将被解析没有问题。
猜你喜欢
  • 2012-11-19
  • 1970-01-01
  • 2016-02-14
  • 1970-01-01
  • 2016-12-30
  • 1970-01-01
  • 1970-01-01
  • 2014-09-01
  • 2012-03-20
相关资源
最近更新 更多