doushi4633 2013-08-30 02:58
浏览 23
已采纳

如何在php中验证表单

I'm hoping there is a solution for this, I'm a noob in php, I couldn't figure it out.

I got some help from here, to validate the html form in php. It is working ok..but I found that after I hit the submit button & php shows the errors, there is a input field, asking the user to answer the math Ques..when I enter the answer, then hit submit button again, it just says mail successfully sent, but other fields are still empty. Any ideas how to fix it. Also, the php value in the answerbox input tags, is not saving the text in box, it disappears.

Thanks for ur time!

<div id="contact">
  <h1 class="heading1"> Contact:</h1>
  <form name="contact" action="formtest.php" method="post">
    <label for="YourName">Your Name:</label>
    <input type="text" name="name" class="required" value="<?= isset($_POST['name']) ? $_POST['name'] : '' ?>" />

    <label for="YourEmail">Your Email:</label>
    <input type="text" name="email" class="required" value="<?= isset($_POST['email']) ? $_POST['email'] : '' ?>"/>

    <label for="Subject">Subject:</label>
    <input type="text" name="subject" class="required" value="<?= isset($_POST['subject']) ? $_POST['subject'] : '' ?>" />

    <label for="YourMessage">Your Message:</label>
    <textarea  name="message" class="required"><?= isset($_POST['message']) ? $_POST['message'] : '' ?></textarea>
    <p class="c3">10 + 5 =<input type="text" name="answerbox" id="answerbox" "<?= isset($_POST['answerbox']) ? $_POST['answerbox'] : '' ?>"/></p>

    <fieldset>
      <input type="submit" name="submit" id="submit" value="Send" class="required"/>
      <input type="reset" id="reset" value="Reset"/>    
    </fieldset>

    <?php
      if(isset($_POST['submit'])){
        $name = trim($_POST["name"]);
        $email = trim($_POST["email"]);
        $subject = trim($_POST["subject"]);
        $message = trim($_POST["message"]);
        $answerbox = trim($_POST["answerbox"]);
        if(empty($_POST['name'])){
          print "<div class='formerrors'><li>Please type your name.</li></div>";
        }
        else {
          if (ctype_alpha($name) === false) {
            print "<div class='formerrors'><li>Your name only should be in letters!</li></div>";
          }
        }

        if(empty($_POST['email'])){
          print "<div class='formerrors'><li>You've forgot to type your email address.</li></div>";
        } else{
          if(filter_var($email, FILTER_VALIDATE_EMAIL) === false){
            print "<div class='formerrors'><li>Your email is not valid, please check.</li></div>";
          }
        }

        if(empty($_POST['subject'])){
          print "<div class='formerrors'><li>Please type a subject.</li></div>";
        }

        if(empty($_POST['message'])){
          print "<div class='formerrors'><li>You've forgot to type your message.</li></div>";
        }

        if(empty($_POST['answerbox'])){
          print "<div class='formerrors'><li>Please answer the math question.</li></div>";
        }
        else {
          if($answerbox != 15){
              print"<div class='formerrors'><li>Answer is not correct.</li></div>";
          }
          else{
            $headers =  'From: '.$email. "
" .
            'Reply-To: '.$email . "
" .
            'X-Mailer: PHP/' . phpversion();
             mail('me@mymail.me',$subject,$message,$headers);
            print "<div class='formerrors'><li>mail succesuffully sent</li></div>";
          }
        }
      }
    ?>
  </form>
</div><!--contact-->
  • 写回答

1条回答 默认 最新

  • dpr26232 2013-08-30 03:13
    关注

    As you are a newcomer to PHP I would give you some tips for a beginner as I can.

    First is that you are outputting an HTML code and processing PHP afterwards. This might not be a good practice (and solution to your problem is quite connected to this). What you are doing is showing a form all the time, without restrictions and checking/validating via PHP afterwards. A good practice is to never output html code before any kind of php goes (there are other issues like of header() function besides your example).

    What you would rather do is:

    <?php
      if (isset($_POST['submit'])) {
      // validations here
      // if (......) { echo 'problem 1...'; }
      // elseif (.....) { echo 'problem 2...'; }
      // else (.....} {
         // No problems so we can send it
         // mail(.....);
      //   }
      }
    
    // done with PHP now show HTML
    ?>
    <form>....</form>
    

    Another thing I would give you as a tip is that when building static pages like that (I mean less structured, less object oriented, you know..) a good practice is to store what your are 'echoing / printing' in variables and output them nicely where applicable.

    So instead of

    <?php
      if (empty($user)) { echo 'Username is empty!'; } // Directly echoing (perhaps in not a right place, maybe even before <!DOCTYPE><html> declaration!!
    ?>
    

    You would go with

    <?php
       $errors = '';
       if (empty($user)) { $errors .= '<br/>Error1: Provide an username'; }
       elseif (empty($name)) { $errors .= '<br/>Error2: Provide a name'; }
       else { /*.....*/ } 
       // Since we have our errors variable with errors (or empty one) we can check for it perhaps in HTML context
    ?>
    <form>
      <?php if (!empty($errors)) { ?>
        <div style='color:red;'>There are some errors! :(</div>
        <?php echo $errors; ?>
        </div>
      <?php } ?>
    </form>
    

    I hope these humble opinions will help you at least maybe to solve your problem. Good luck

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路