Header and Echo dilemma


Header and Echo dilemma

我在一个正在开发的网站上有一个联系人表单,我写了一些PHP,如果某些字段没有正确填写,就会向页面返回错误,一切正常,如果填写正确,就会发送电子邮件,如果不正确,就会发出并显示错误消息。

唯一的问题是,如果表单填写错误,用户会被重定向到带有错误消息的页面,但表单会在页面下方重定向到用户所在的位置。我希望如果有一个错误,用户被重定向到同一个页面,并返回错误消息,但在表单所在的页面下方。

我做了一些研究,发现我可以使用id锚点和页眉,但如果我这样做,页面确实会加载到我告诉它的位置,但错误消息不会显示。我曾尝试使用带有_GET变量的if循环来检查它是否与错误消息中的内容匹配,但似乎无法使任何内容正常工作。

所以总结一下:
如果表单填写错误,我希望用户返回到同一页面,但向下显示表单所在的位置,并在表单上方显示代码中设置的错误消息变量。

我刚开始学习PHP,所以我很感激你能帮我解决这个问题。提前感谢您的帮助和建议。

以下是该网站的一些屏幕截图:
http://imgur.com/a/Hv5OW

这是页面的代码:

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $name    = trim($_POST["name"]);
    $email   = trim($_POST["email"]);
    $message = trim($_POST["message"]);
    if ($name == "" OR $email == "" OR $message == "") {
        $error_message = "You must enter a name, email address and message";
    }
    if (!isset($error_message)) {
        foreach ($_POST as $value) {
            if (stripos($value, 'Content-Type:') !== false) {
                $error_message = "There was a problem with the information you submitted";
            }
        }
    }
    if (!isset($error_message) && $_POST["address"] != "") {
        $error_message = "Your contact form submission has an error";
    }
    require_once("inc/phpmailer/class.phpmailer.php");
    $mail = new PHPMailer();
    if (!isset($error_message) && !$mail->ValidateAddress($email)) {
        $error_message = "You must specify a valid email address";
    }
    if (!isset($error_message)) {
        $email_body = "";
        $email_body = $email_body . "Name: " . $name . "<br>";
        $email_body = $email_body . "Email: " . $email . "<br>";
        $email_body = $email_body . "Message: " . $message;
        $mail->SetFrom($email, $name);
        $address = "name@email.co.uk";
        $mail->AddAddress($address, "Corwen Forestry Timber Products Ltd.");
        $mail->Subject = "Website Contact Form Submission | " . $name;
        $mail->MsgHTML($email_body);
        if ($mail->Send()) {
            header("Location: contact.html?status=thanks");
            exit;
        }
        else {
            $error_message = "There was a problem sending the email: " . $mail->ErrorInfo;
        }
    }
}
;
?>
<?php
$title = "Corwen Forestry Online | Contact Us";
$active = "contact";
include("inc/header.php");
?>
    <img class="banner" src="images/contact-us.jpg" alt="Contact us background image.">
    <article class="band content-wrap clearfix">
        <?php if (isset($_GET["status"]) && $_GET["status"] == "thanks") { ?>
            <section>
                <p class="contact-thanks">Thanks for getting in touch, we'll get back to you as soon as we can.</p>
            </section>
        <?php }
        else { ?>
            <header>
                <h2>Contact Us</h2>
            </header>
            <section class="contact-intro">
                <p>
                    Lorizzle hizzle dolor fizzle amizzle, consectetuer adipiscing elizzle. Crackalackin sapien velizzle,
                    my shizz volutpizzle, suscipit quis, its fo rizzle vel, arcu. Pellentesque fizzle tortizzle. Izzle
                    mammasay mammasa mamma oo sa. Fusce izzle dolor dapibus turpis tempizzle tellivizzle. Crunk
                    pellentesque nibh izzle turpizzle. Fo shizzle my nizzle funky fresh crackalackin. Pellentesque
                    eleifend rhoncizzle nisi. In for sure habitasse platea dictumst. Donec dapibizzle. Curabitur gangsta
                    urna, pretizzle eu, pizzle ac, my shizz vitae, nunc. Da bomb suscipizzle. Integer break it down
                    pimpin' shiznit fo shizzle my nizzle.
                </p>
            </section>
            <section id="error-anchor" class="contact-third first">
                <img src="images/contact-icon-email.png" alt="email icon">
                <h3><a href="mailto:sales@corwenforestry.co.uk">sales@corwenforestry.co.uk</a></h3>
            </section>
            <section class="contact-third">
                <img src="images/contact-icon-address.png" alt="address icon">
                <h3>
                    Ty&rsquo;n Llidiart Industrial Estate<br>
                    Corwen<br>
                    Denbighshire<br>
                    LL21 9RZ
                </h3>
            </section>
            <section class="contact-third">
                <img src="images/contact-icon-phone.png" alt="phone icon">
                <h3>01490 412 146</h3>
            </section>
            <?php
            if (isset($error_message)) {
                header("Location: contact.html#error-anchor");
                echo '<p class="error-message">' . $error_message . '</p>';
            }
        ;
            ?>
            <form class="clearfix" method="post" action="contact.html">
                <table class="contact-us">
                    <tr>
                        <th>
                            <label for="name">Name</label>
                        </th>
                        <td>
                            <input type="text" name="name" id="name">
                        </td>
                    </tr>
                    <tr>
                        <th>
                            <label for="email">Email</label>
                        </th>
                        <td>
                            <input type="text" name="email" id="email">
                        </td>
                    </tr>
                    <tr>
                        <th>
                            <label for="message">Message</label>
                        </th>
                        <td>
                            <textarea name="message" id="message"></textarea>
                        </td>
                    </tr>
                    <tr style="display: none;">
                        <th>
                            <label for="address">Address</label>
                        </th>
                        <td>
                            <p>Please leave the address field blank, it's an anti-spam measure.</p>
                            <input type="text" name="address" id="address">
                        </td>
                    </tr>
                </table>
                <input type="submit" value="Send Message">
            </form>
            <section class="map">
                <iframe width="47.7%" height="350" frameborder="0" scrolling="no" marginheight="0" marginwidth="0"
                        src="https://maps.google.co.uk/maps/ms?msa=0&amp;msid=208085933608816427574.0004e1242973ccf3517ee&amp;ie=UTF8&amp;t=m&amp;ll=52.977589,-3.414001&amp;spn=0.144707,0.291824&amp;z=11&amp;output=embed"></iframe>
                <br/>
                <small>View <a target="_blank"
                               href="https://maps.google.co.uk/maps/ms?msa=0&amp;msid=208085933608816427574.0004e1242973ccf3517ee&amp;ie=UTF8&amp;t=m&amp;ll=52.977589,-3.414001&amp;spn=0.144707,0.291824&amp;z=11&amp;source=embed"
                               style="color:#0000FF;text-align:left">CFTP HQ and Mills</a> in a larger map
                </small>
            </section>
            <section class="map-key">
                <ul>
                    <li>
                        <img src="images/a-sml.png" alt="Head Office map icon key.">
                        Head Office &amp; Shop
                    </li>
                    <li>
                        <img src="images/b-sml.png" alt="Gwyddelwern Sawmill map icon key.">
                        Gwyddelwern Sawmill
                    </li>
                    <li>
                        <img src="images/c-sml.png" alt="Llandrillo Sawmill map icon key.">
                        Llandrillo Sawmill
                    </li>
                </ul>
            </section>
        <?php } ?>
    </article><!-- end band content-wrap -->
<?php include("inc/footer.php"); ?>

根据您的问题,您可以使用以下方法:

我们的想法是在submit上"锚定"表单——这允许我们在按下提交按钮后立即进入表单,无论表单验证是否成功。

1) 设置一个"锚"-像这样的动作:

<form class="clearfix" method="post" action="contact.html#myAnchor">

2) 在表单上方设置一个"假"url,如下所示:

<a href="#myAnchor"></a> 
<form class="clearfix" method="post" action="contact.html#myAnchor">

您可以按照自己喜欢的方式设置样式,或者在form标记中使用id="myAnchor"(如果它不破坏任何内容)

3) 使用您当前的代码,乍一看很好:

if (!isset($error_message)) {
   // Send mail
} else {
   // do everything you want with error variable.
}

4) 在表单的正上方回显错误

<a href="#myAnchor"></a>
<?= $sFormattedErrorVariable ?>
<form class="clearfix" method="post" action="contact.html#myAnchor">

希望这能有所帮助。干杯

我相信你想要这样的东西。如果你发布的表单不正确,它应该将用户重定向到一个链接,如:

Header('Location: contact.html?error=' . $error . '#error-anchor');

要想让它发挥作用,你必须改变几件事;

您的表单需要一个id

<form class="clearfix" method="post" action="contact.html" id="error-anchor">

为了保持您的url干净,您可能需要更改错误处理,例如更改:

if ($name == "" OR $email == "" OR $message == "") {
    $error_message = "You must enter a name, email address and message";
}

if ($name == "" OR $email == "" OR $message == "") {
    $error = 1; //to use in your redirect url
}

在页面顶部,您需要检查$_GET['error]是否已设置(在重定向后使用),并相应地设置消息:

if ($_GET['error']) {
    switch ($_GET['error']) {
        case 1:
            $error_message = "You must enter a name, email address and message";
            break;
        case 2:
            $error_message = "Other error";
            break;
    }
} else if ($_POST) {
     //form post handling
}

您应该创建更智能的捕获错误。也许会创建一个错误数组并添加新的错误。比如:

$error_message = array();
...
// $error_message[ID_MSG]
$error_message[2] = "text of msg";
...
<td>
 <input <?php
  if(isset($error_message[2])) {
   echo 'value="' . $email . '" class="errorStyle"';
  }
 ?> type="text" name="email" id="email">
</td>
...

对于计数错误,使用一些类似:

count($error_message) > 0