【问题标题】:Show errors on form without using $_GET不使用 $_GET 在表单上显示错误
【发布时间】:2019-07-12 17:19:05
【问题描述】:

我使用 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();
}

【问题讨论】:

  • 请分享一些代码,以便我们了解您是如何解决问题的
  • 您可以使用会话来临时存储信息。
  • 添加了我的代码,忘记了
  • if (empty($name) or empty($email) or empty($pwd) or empty($pwd2)) { // echo 'please fill the form'; }....

标签: php forms post get


【解决方案1】:

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

在以下示例中,我们将 errorsdata 设置为会话,以便我们可以从 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...

}

【讨论】:

    【解决方案2】:

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

    使用这种方法,您不需要在发现错误时进行大量重定向

    页面顶部有 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>
    ...
    

    【讨论】:

    • 赞成。我会回答完全一样的,戴夫。他还可以检查会话以避免提交重复
    • 我想避免页面本身的表单验证。这只是我的编码方式
    • 那么您必须使用会话来跟踪错误并重新填充表单。查看快讯
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-20
    • 2014-03-28
    相关资源
    最近更新 更多