【问题标题】:How to check for form submission in PHP?如何在 PHP 中检查表单提交?
【发布时间】:2016-07-28 13:19:24
【问题描述】:

在我的表单中,有一些字段,我想在提交表单之前检查它们。如果有错误,表单将不会被提交,用户会收到错误警告。

为此,我试图在 php.ini 中捕获提交表单的事件。我应该收到带有“已提交”文本的警报。但是,我没有。我做错了什么?

<?php
if(isset($_POST['submit']))
    echo "<span>Submitted!</span>";
    sleep(2);
?>

<form action="next_page.php" method=post> 
*Other fields beside input*
<input type="submit" name="submit" value="Submit form"> <br>
</form>

【问题讨论】:

  • HTML5 pattern 属性或者你可以使用 JS。哦,submit 输入!
  • 您是否在该表单的任何位置看到了名为“submit”的表单元素?不?我也没有。那么你怎么能期望在你的代码中看到它呢?
  • 看起来您正在混合使用 javaScript 和 PHP(除非您编写了自己的 alrt() 函数,但基于这个问题的简单性,我非常怀疑)。
  • 警报? Javascript警报?来自你的 PHP 脚本?!
  • alert() 是一个 JAVASCRIPT 函数。因此它在你的 PHP 中什么都不做,除了它应该生成一个编译错误。查看 PHP 错误日志

标签: php html forms


【解决方案1】:

alert()不是PHP提供的函数,所以会报错。

您似乎将它与 JavaScript 混淆了。

要从 PHP 输出文本,您需要 echo 或将其放在 &lt;?php ... &gt;? 块之外。要运行 JavaScript,您需要一个 &lt;script&gt; 元素。

<?php
if(isset($_POST['submit'])) {
?>
    <script> alert("Submitted!"); </script>
<?php
}
?>

<form action="next_page.php" method=post> 
    <!-- You also need to have a form control that matches the test you are doing -->
    <button name="submit" value="X">Submit</button>
</form>

【讨论】:

    【解决方案2】:

    您的表单缺少submit 类型。 您还需要echo 警告框,因为alert() 不是 PHP 函数。

    <?php if(isset($_POST['submit']))
        echo"<script>alert('Submitted!');</script>"; ?>
    
    <form action="next_page.php" method=post>  
    <input type = "submit" name = "submit" value = "Sub"/> 
    </form>
    

    【讨论】:

      【解决方案3】:

      据我了解,您在提交表单后尝试在同一页面上输出消息,而不是警报。 HTML 表单标签上的 action 属性将您重定向到 next_page.php。所以将 action 属性留空,并在验证完所有字段后使用 php header() 函数重定向到 next_page.php。请注意不要在 header() 函数之前输出任何消息,在这种情况下它将失败。 做这样的事情:

      <?php
      if( $_SERVER['REQUEST_METHOD'] == 'POST' ){
          $err_message = '';
          //validate your fields
          if($_POST['yourfield'] == ''){
              $err_message = 'Please check your fields';
          }
          //other validations
          ...
          if($err_message == ''){
             //redirect to your next page
             header('Location:next_page.php');
             //prevent further code execution
             exit();
          }
          //output your message
          echo $err_message;
      }
      ?>
      
      <form action="" method=post> 
      *Other fields beside input*
      <input type="submit" name="submit" value="Submit form"> <br>
      </form>
      

      【讨论】:

        【解决方案4】:

        有很多方法可以做到。

        如果你想让它基于回声,这里又是一个替代方案:

        <?php
        if (isset($_POST['submit']))
        {
            echo '<script>alert("Submitted!");</script>';
        }
        ?>
        
        <form action="" method=post>
            *Other fields beside input*
            <input type="submit" name="submit" value="Submit form"> <br>
        </form>
        

        编辑:通常我会尝试将 PHP 留在同一页面的顶部,而不是将其指向其他地方,因为没有太多需要这样做。

        【讨论】:

          【解决方案5】:

          我解决它的方法是使用 Jquery,如下所示。

          $('#form1').submit(
              function() {
                  //your validation rules here
                  var email = $('#YourEMail').val()
                  if(!validEmail(email))
                  {
                      $('#invalidAlert').html('<i>Invalid e-mail address!</i>')
                      return false;
                  }
                  else 
                      return true;
              });
          

          【讨论】:

            【解决方案6】:

            有很多方法可以完成您想要完成的事情。您是否使用任何类型的框架?它可能是为此而内置的。一般来说,依靠标准函数或库来进行验证并不是一个坏主意。

            如果不是,您将不得不自己做,并决定您希望它是服务器端 (php) 还是用户端 (javascript)。无论如何,您都应该在服务器端验证它以捕获任何恶意提交。

            如果我们使用您的示例,服务器端 php 验证可能看起来像这样,它将结果回显给用户。请注意,这真的非常不安全,因为它使用了可能被修改的 $_GET 等。

            <?php
            $username = '';
            $warning = '';
            
            if(isset($_POST['submit'])){
                if(!empty($_POST['username']) && strlen(trim($_POST['username'])) != 0){
                    $username = $_POST['username'];
                    if(strlen($username) > 8){
                        $warning = 'Only 8 characters allowed!';
                    }else{
                        header("Location: next_page.php");
                    }
                }
                else
                {
                    $warning = 'Username is empty, please provide a valid name.';
                }
            }
            ?>
            <form action="form.php" method="post"> 
                <input type="text" name="username" value="<?php echo($username); ?>" />
                <?php echo($warning); ?>
                <input type="submit" name="submit" />
            </form>
            

            这个 sn-p 将保留输入以防出现任何错误,并且仅在数据有效时才重定向到下一页。使用 jQuery 的示例可能如下所示:

            <html lang="en">
            <head>
              <meta charset="utf-8">
              <title>event.preventDefault demo</title>
              <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
            </head>
            <body>
            
            
                <form action="form.php" method="post"> 
                    <input type="text" name="username" id="formUsername" />
                    <span id="warning"> </span>
                    <input type="submit" name="submit" />
                </form>
            
                <script>
                $(document).ready(function() {
            
                    $("form").submit(function( event ) {
                        var username = $("#formUsername").val().trim();
            
                        if(username.length > 0 && username.length < 9){
                            $("form").submit();
                        }
                        else if(username.length > 8)
                        {
                            $("#warning").text("More than 8 characters.");
                            event.preventDefault();
                        }
                        else{
                            $("#warning").text("Empty username?");
                            event.preventDefault();
                        }
                    });
            
                });
                </script>
            </body>
            </html>
            

            【讨论】:

            • 您在第一个示例中混合了$_GET$_POST,表单仍然通过POST 提交,并且您的第二行将抛出UNDEFINED Variable,除非用户名是通过URL 设置的。 (仅在第一个示例中)
            • 谢谢,我确实改进了一点。起初我的想法不同,因此与$_GET 混淆了。它只是为了让某人知道可以做什么。它有很多缺陷。
            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2016-02-04
            • 2011-12-04
            • 2019-07-26
            • 2014-09-13
            • 1970-01-01
            相关资源
            最近更新 更多