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



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

<?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>

我正在编写代码,但当我发现它不起作用时,我正在询问如何解决此问题以及如何安全地实现发布/重定向/模式,我知道它可以工作。

请参阅通过传递验证消息.phpsubmit-registerPOST 操作验证并重定向到索引。您需要从标头方法传递消息。

在 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");
}
}

请注意,在标题方法之前,页面上不应打印任何内容。这意味着在标头方法之前根本没有回显。

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

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

使用 header(path( 重置页面。 因此,之前打印的任何回声都将被丢弃。

最新更新