如果输入字段为空,PHP 不会回显;与 PRG 模式

标签 php html http post-redirect-get

我对如何在 PHP 中实现 Post/Redirect/Get 模式有些困惑。我看到一些答案说在提交表单后只需添加 header 功能;我已经这样做了,但是在验证输入字段是否为空时,它不会打印任何内容,尽管我在运行代码后添加了 header 函数。我根本找不到如何整合它,所以我还是要问。

<?php

require '../BACKEND/DB/DB_CONN.php';

if(isset($_POST['submit-register'])) {

    if(empty($_POST['email'])) {
        echo 'Email cannot be nothing.';
    }

    header("Location: index.php");
    die();
}

if(isset($_POST['submit-login'])) {

    if(empty($_POST['loginUser'])) {
        echo 'Field Empty.';
    }

    header("Location: index.php");
    die();

}

?>

<div class="forms">
        <form method="post" action="index.php" role="form" class="forms-inline register ">
        <h4>Register</h4>
            <input type="text" name="email" placeholder="Email Address" autocomplete="off" />
            <input type="text" name="username" placeholder="Username" autocomplete="off" />
            <input type="password" name="password" placeholder="Password" autocomplete="off" />
            <input type="submit" name="submit-register" value="Register" role="button" name="login-btn" />
        </form>
        <form method="post" action="index.php" role="form" class="forms-inline login ">
        <h4>Login</h4>
            <input type="text" name="loginUser" placeholder="Username" />
            <input type="password" name="loginPass" placeholder="Password" />
            <input type="submit" name="submit-login" value="Register" role="button" />
        </form>
    </div>

我正在编写代码,但我发现它不起作用,我想问一下如何解决这个问题以及如何安全地实现 Post/Redirect/Pattern 并且我知道它有效。

最佳答案

查看 submit-register POST 操作验证并通过传递验证消息重定向到 index.php。您需要获取从 header 方法传递的消息。

在 PRG 模式中,当您执行具有数据的 POST 操作但是当您重定向并在发布后执行 GET 以维护 PRG 时,您必须将数据传递到最后一个目标 GET url。

在您的代码中,查看我所做的两种方式,第一种方式将您的消息传递给索引,第二种方式在验证发生错误时不传递 PRG。

//PRG..........................................
if(isset($_POST['submit-register'])) {

    if(empty($_POST['email'])) {
        echo 'Email cannot be nothing.';
        $msg = "Email cannot be nothing";
    }

    header("Location: index.php?msg=$msg");
    //Get your this message on index by $_GET //PRG

}
//Not full PRG with no passing data to destination.........................
if(isset($_POST['submit-login'])) {

    if(empty($_POST['loginUser'])) {
        echo 'Field Empty.';
    }
    else{
        header("Location: index.php");
    }

}

注意header方法前页面不能打印任何东西。这意味着在 header 方法之前没有回显。

请看第一个是 PRG,第二个也是 PRG,但没有将您的数据传递到目的地。

header("Location: index.php?msg=$msg");

关于如果输入字段为空,PHP 不会回显;与 PRG 模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45488789/

相关文章:

javascript - 我得到每个按钮的相同值

javascript - AJAX 函数未触发

html - HTML anchor 标记中超链接文本的内联换行

html - 嵌套元素的交替背景颜色

api - 404 状态码及其在常见的、几乎静态的 api 上的双重含义

php - 对于 php 中的 mysql,例如在 jquery 中,是否有一种简单的方法来获取 "roll your own forms"?

javascript - 如何以编程方式将表格滚动到特定的 tr

http - 如何通过 http url 发送二进制数据(del 和 null 字符)

php - 使用 PECL HTTP 类在 PHP 中进行并行 HTTP 请求 [答案 : HttpRequestPool class]

甚至在输出缓冲区内发送 PHP header 位置?