PHP表单提交前显示错误消息的联系表单

PHP表单提交前显示错误消息的联系表单

问题描述:

I am using a simple PHP contact form which is working well. But when you load a page for the first time it always gives the error message 'Please Supply all Information'

Can anyone see why this is happening?

<?php
  $response = "";  

  function my_contact_form_generate_response($type, $message){
    global $response;
    if($type == "success") $response = "<div class='success'>{$message}</div>";
    else $response = "<div class='error'>{$message}</div>";
  }

  $missing_content = "Please supply all information";
  $message_unsent  = "Message was not sent. Try Again";
  $message_sent    = "Thanks! Your message has been sent";

  $name = $_POST['message_name'];
  $phone = $_POST['message_phone'];

  $to = 'test@example.com';
  $subject = "Someone sent a message from ".get_bloginfo('name');
  $headers = 'From: '. $email . "
" .
    'Reply-To: ' . $email . "
";

        if(empty($name) || empty($phone)){
          my_contact_form_generate_response("error", $missing_content);
        }
        else
        {
          $sent = wp_mail($to, $subject, strip_tags($name), $headers);
          if($sent) my_contact_form_generate_response("success", $message_sent); //message sent!
          else my_contact_form_generate_response("error", $message_unsent); //message wasn't sent
        }
        ?>

        <form action="<?php the_permalink(); ?>" method="post" role="form">
                <?php echo $response; ?>
                <div class="form-group">
                    <label>Name:</label>
                    <input class="form-control" type="text" name="message_name">
                </div>
                <div class="form-group">
                    <label>Phone</label>
                    <input class="form-control" type="text" name="message_phone">
                </div>
                <div class="button-group">
                <button type="submit" class="btn">Submit</button>
                </div>
            </form>
        </div>
    </div>

It's because you're not checking to see if the form is submitted. You're just executing that code on every page load. You can

Check if the submission was via POST

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // your code here
}

Or check if the submit button was pressed

<input type="submit" name="submit" class="btn">Submit</input>

if (isset($_POST['submit'])) {
    // your code here
}