首页 > 解决方案 > 调整交钥匙 PHP 表单以在与表单相同的页面上显示错误消息

问题描述

我有一个可操作的网络表单,当前将错误发送到新页面,即下面 PHP 的$myError部分。

你能帮我调整这些代码片段,以便错误显示在同一页面上,最好是在表格的顶部。

我知道这可能会包含会话,但不知道如何修改我现有的代码。

谢谢!!

这是 HTML:

<form method="post" action="contact.php">
<div class="fields">
    <div class="field half">
        
        <input type="text" name="name" id="name" placeholder="Name"/>
        <label for="name">Your Name</label>
    </div>
    <div class="field half">
        
        <input type="text" name="email" id="email" placeholder="Email"/>
        <label for="email">Your Email</label>
    </div>
    <div class="field">
        
        <input type="text" name="subject" id="subject" placeholder="Subject"/>
        <label for="email">Your Subject</label>
    </div>
    <div class="field">
        
        <textarea name="message" id="message" rows="3" placeholder="What's on your mind?"></textarea>
        <label for="message">Your Message</label>
    </div>
</div>
<ul class="actions">
    <li><a type="submit" class="button large submit">Send Message</a></li>
</ul>
</form>

这是PHP:

<?php
/* Set e-mail recipient */
$myemail  = "me@dom.ain";

/* Check all form inputs using check_input function */
$yourname = check_input($_POST['yourname'], "Enter your name");
$subject  = check_input($_POST['subject'], "Write a subject");
$email    = check_input($_POST['email']);
$message = check_input($_POST['message'], "Write your message");

/* If e-mail is not valid show error message */
if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/", $email))
{
    show_error("E-mail address not valid");
}

/* Let's prepare the message for the e-mail */
$message = "Hello!

Your contact form has been submitted by:

Name: $yourname
E-mail: $email
URL: $website

message:
$message

End of message
";

/* Send the message using mail() function */
mail($myemail, $subject, $message);

/* Redirect visitor to the thank you page */
header('Location: thanks.html');
exit();

/* Functions we used */
function check_input($data, $problem='')
{
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    if ($problem && strlen($data) == 0)
    {
        show_error($problem);
    }
    return $data;
}

function show_error($myError)
{
?>
    <html>
    <body>

    <b>Please correct the following error:</b><br />
    <?php echo $myError; ?>

    </body>
    </html>
<?php
exit();
}
?>

标签: phpformsemailsession

解决方案


推荐阅读