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 关于logstash转发日志时发生的部分内容丢失问题
  • ¥17 pro*C预编译“闪回查询”报错SCN不能识别
  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?