我正在使用一个非常简单的表单并尝试学习php。我有会话工作和发布数据工作,但我试图将用户重定向到下一页,如果数据有效。我正在运行一些验证,到目前为止我也很成功,但只有我找不到的是如果他们在表单中输入的数据是有效的,如何进入下一页。如果不是它已经打印错误。我是新手,所以任何帮助将不胜感激。
$nameErr = "";
if($_SERVER["REQUEST_METHOD"] == "POST"){
if(empty($_POST["fname"])){
$nameErr = "name is required";
}
}
这就是我的表单的样子。我知道我必须在表单的“动作”部分更改某些内容,因为它现在正在打印到相同但不确定是什么。我可以写一个if语句吗?
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<label for="fname">FirstName:</label>
<input type="text" class="form-control" name="fname" id="fname" placeholder="Enter First Name">
<span class="error">* <?php echo $nameErr;?></span>
答案 0 :(得分:4)
您可以使用 PHP header
header("Location: /example/par1/");
exit();
在你的情况下:
$nameErr = "";
if($_SERVER["REQUEST_METHOD"] == "POST")
{
if(empty($_POST["fname"]))
{
$nameErr = "name is required";
}
else
{
// If validation success, then redirect
header("Location: http://www.google.com/");
exit();
}
}
注意:强>
是的,正如 @Andrei P 在评论中所说,header()
被调用之前不应该是任何事情。更准确地说,应在PHP打开标记<?php
之后调用标题函数。例如,
<?php
header('Location: http://www.example.com/');
exit;
下面会给您一个错误
<html>
<?php
/* This will give an error. Note the output
* above, which is before the header() call */
header('Location: http://www.example.com/');
exit;
?>
有关详细信息,请参阅this。