douyi9447 2014-10-23 18:44
浏览 42
已采纳

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>
  • 写回答

1条回答 默认 最新

  • dongtiandexue123456 2014-10-23 18:45
    关注

    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
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大