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

时间:2014-10-23 18:44:03

标签: php forms

我正在使用一个运行良好的简单PHP联系表单。但是,当您第一次加载页面时,它始终会显示错误消息“请提供所有信息”

有人能看出为什么会这样吗?

<?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 . "\r\n" .
    'Reply-To: ' . $email . "\r\n";

        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>

1 个答案:

答案 0 :(得分:2)

这是因为您没有检查表单是否已提交。您只是在每个页面加载时执行该代码。你可以

检查提交是否通过POST

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

或检查是否按下了提交按钮

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

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