在不使用$ _GET的情况下在表单上显示错误

时间:2019-07-12 17:19:05

标签: php forms post get

我使用PHP创建了注册表。提交表单时,我检查是否有错误(是否使用名称或电子邮件,并且密码均正确)。如果出现问题,我使用header函数以及信息(错误和字段)将用户返回到表单,然后使用$_GET方法显示错误并重新填写表单。

有没有一种方法可以在不使用header$_GET的情况下在表单上显示错误?我可以从$_POST接收错误信息并重新填写表格吗?

我不想使用JavaScript,但会在需要时使用

我的代码运行良好,只是想知道是否有一种方法可以不使用URL。

我的注册表格:

<?php
  require 'header.php';
?>

<section>
  <?php
    if (isset(&_GET['error'])) {
      // My error code here...
    }
  ?>
  <form action="inc/register.inc.php" method="post">
    <input type="text" name="name" placeholder="Name" value="<?php $_GET['name'] ?>" />
    <input type="text" name="mail" placeholder="E-mail" value="<?php $_GET['mail'] ?>" />
    <input type="password" name="pwd" placeholder="Password" />
    <input type="password" name="pwd-repeat" placeholder="Confirm Password" />
    <input type="submit" name="registerBtn" value="Registreer" />
  </form>
</section>

<?php
  require 'footer.php';
?>

处理错误和注册的php文件:

<?php
if (isset($_POST['registerBtn'])) {
  require 'db_connect.php';

  $name = $_POST['name'];
  $email = $_POST['mail'];
  $pwd = $_POST['pwd'];
  $pwd2 = $_POST['pwd-repeat'];

  if (empty($name) or empty($email) or empty($pwd) or empty($pwd2)) {
    header("Location: ../register.php?error=emptyfields&name=". $name ."&mail=". $email);
    exit();
  }
  else if (!preg_match("/^[\p{L}\p{N}_-]*$/u", $name) and !filter_var($email, FILTER_VALIDATE_EMAIL)) {
    header("Location: ../register.php?error=invalidmailname);
    exit();
  }
  else if (!preg_match("/^[\p{L}\p{N}_-]*$/u", $name)) {
    header("Location: ../register.php?error=invalidname&mail=". $email);
    exit();
  }
  else if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    header("Location: ../register.php?error=invalidmail&name=". $name);
    exit();
  }
  else if ($pwd !== $pwd2) {
    header("Location: ../register.php?error=passwordcheck&name=". $name ."&mail=". $email);
    exit();
  }
  else {
    // More code here... but you get the gist.
  }
}
else {
  header("Location: ../register.php");
  exit();
}

2 个答案:

答案 0 :(得分:1)

“回发”是指发件人向自身提交(同一页)。

通过这种方法,发现错误时无需进行大量重定向

页面顶部有PHP,其内容如下:

$error_text = "";
if (isset($_POST['submit_button'])) {
    ... validate all data ....
    ... adding to $error_text for any errors found ...
    if ($is_valid)
        ... process form ...
        ... display results page & exit()
    else
        ... fall through to displaying form page below
} // end of form submit handling

// if we reach here, either there was no form submit (first time page displayed)
// or the form was submitted but errors were found and $error_txt is now something like 
// <p>Error: passwords must match</p>
?>

<html>
...
<?php echo $error_txt; ?>
<form>
...

答案 1 :(得分:1)

如果您想使用单独的脚本来处理表单,则可以使用会话保存临时数据-这通常称为 flash数据

在下面的示例中,我们为会话设置了 errors data ,以便我们可以从index.php访问它。

在处理了Flash数据之后,我们将其从会话中删除,因为我们不希望它在下一个请求中出现。

index.php     

session_start();

// The values that are used to display the form after validation has failed.
// Notice that we actually set them below using the flash data if it's available.
$firstName = '';
$lastName = '';

// Do we have any flash data to deal with?
if (isset($_SESSION['flash'])) {

    // Here, we deal with any _errors_
    if (isset($_SESSION['flash']['errors'])): ?>

        <ul>
            <?php foreach ($_SESSION['flash']['errors'] as $field => $error): ?>
                <li><?php echo $error; ?></li>
            <?php endforeach; ?>
        </ul>
    <?php endif;

    // Here we deal with populating the form again from _data_
    if (isset($_SESSION['flash']['data'])) {
        $firstName = $_SESSION['flash']['data']['first_name'] ?: '';
        $lastName = $_SESSION['flash']['data']['last_name'] ?: '';
    }

    // Remove the flash data from the session since we only want it around for a single request
    unset($_SESSION['flash']);
}
?>
<form method="post" action="handler.php">

    <label>
        <input type="text" name="first_name" placeholder="First Name" value="<?php echo $firstName; ?>">
    </label>

    <label>
        <input type="text" name="last_name" placeholder="Last Name" value="<?php echo $lastName; ?>">
    </label>

    <input type="submit" name="submit">
</form>

handler.php     

session_start();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $firstName = $_POST['first_name'] ?: null;
    $lastName = $_POST['last_name'] ?: null;

    $errors = [];

    if (empty($firstName)) {
        $errors['first_name'] = 'Please enter your first name';
    }

    if (empty($lastName)) {
        $errors['last_name'] = 'Please enter your last name';
    }

    // If we have errors, set up our flash data so it is accessible on the next request and then go back to the form. 
    if ($errors) {
        $_SESSION['flash']['errors'] = $errors;
        $_SESSION['flash']['data'] = $_POST;

        header('Location: index.php');
        exit;
    }

    // We know there are no errors at this point so continue processing...

}