如何在 php 中等分表单然后提交


How to alidate a form in php then submit it?

我在提交之前使用 php 验证我的表单,我想发布到 index.php但我有两个问题:

  1. 如果我执行表单操作来$_SERVER它将在不索引的情况下验证表单.php并在那里触发代码:

    <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" id="contact"  name="contact" method="post"
    

    if ($_SERVER["REQUEST_METHOD"] == "POST") {
        if (empty($_POST["fname"])) {
            $nameErr = "Name is required";
            $hasError = true; 
        } else {
            $name = test_input($_POST["name"]);
        }
    }
    
  2. 如果我这样做action= index.php它会提交表单而不验证:

    <form id="contact" action="index.php" onsubmit="return validateForm()" method="post" >
    

所以我想验证表格然后提交。 有什么建议吗?

给你

几个提示。

  1. 不要使用$_SERVER['PHP_SELF'].请改用action=""

  2. 不要使用 JavaScript 进行验证,除非你有非常复杂的验证要求。

    <input type="text" name="fname" required />
    <input type="email" />
    <input type="number" min="0" max="99" />

    这些只是您可以执行的操作的一些示例,如果验证未通过,所有这些示例都将阻止表单提交,即使浏览器的 JavaScript 被禁用也是如此

  3. 即使您在浏览器中进行了验证(无论是JavaScript还是HTML5表单),您也必须在服务器上验证输入。请记住,如果用户确定,他们可以向您发送他们想要的任何东西,而您只能信任您的服务器。

相关文章: