我希望在点击提交按钮时,如果管理员已登录html页面应重定向到admin.php页面且学生已登录,则应重定向到student.php页面。只会有一个' admin(硬编码)的id-password组合,所以我想知道在php脚本中使用if-else语句是否可以重定向到新的php脚本? 是否可以仅使用一个SUBMIT按钮执行此操作?
<?php
if($_POST['username'] === 'admin' and $_POST['password'] === 'password'){
go to admin.php; //Admin login page
}
else{
go to student.php; //Student has logged in => go to student login page
}
?>
答案 0 :(得分:2)
请参阅location
你可以这样做重定向:
header('Location: /student.php');
请注意:您可能不会在标题功能之前输出任何内容,否则它将无效。
或者你可以用javascript
来做到这一点<script>
window.location = "student.php";
</script>
或使用元刷新
<meta http-equiv="refresh" content="0; url=student.php">
0是延迟,应该重定向。
答案 1 :(得分:2)
试试这个
<?php
if (isset($_POST['submit'])){
if($_POST['username'] === 'admin' && $_POST['password'] === 'password'){
header('Location:admin.php');
}
else if($_POST['username'] === 'student' && $_POST['password'] === 'password'){
header('Location:student.php');
}
else{
header('Location:login.php');
}
}
?>
提交按钮
<input type="submit" name="submit" value="Submit">
答案 2 :(得分:1)
您想要做的事情如下:
<?php
if($_POST['username'] === 'admin' and $_POST['password'] === 'password'){
header('Location:admin.php');
}
else{
header('Location:student.php');
}
?>
这会将用户重定向到您想要的页面。
同样,Rocky说你的标题之前一定不能有任何输出,否则你会收到错误:标题已经发送
答案 3 :(得分:1)
如果该值是硬编码的,那么此代码应该有效:
<?php
if($_POST['username'] === 'admin' && $_POST['password'] === 'password'){
header("Location: admin.php"); //Admin login page
}
else{
header("Location: student.php"); //Student has logged in => go to student login page
}
?>
在大多数情况下,硬编码值不是一个好的选择,但是这个代码就是这样做的。
您甚至可以使用以下元刷新:
<meta http-equiv="refresh" content="0; url=student.php">
还有其他方法可以做到,但我认为你不需要它们。希望这有帮助:)