这里的第一篇帖子如果我在创建帖子时犯了任何错误,请原谅我。 我有以下代码,我想在用户登录时根据用户类型重定向用户。我有以下代码,但我不太清楚如何做到这一点。
<?php
session_start();
if(isset($_SESSION['user_type']) == "S") {
header("Location: /main/studenthome.php");
}
else if(isset($_SESSION['user_type']) == "A") {
header("Location: /main/staffhome.php");
}
include_once 'dbconnect.php';
//check if form is submitted
if (isset($_POST['login'])) {
$username = mysqli_real_escape_string($con, $_POST['username']);
$password = mysqli_real_escape_string($con, $_POST['password']);
$result = mysqli_query($con, "SELECT * FROM users WHERE username = '" . $username. "' and password = '" . md5($password) . "'");
if ($row = mysqli_fetch_array($result)) {
$_SESSION['usr_id'] = $row['usrId'];
$_SESSION['usr_name'] = $row['username'];
$_SESSION['user_type'] = $row["usertype"];
header("Location: /main/studenthome.php");
}
} else {
echo "<div class= 'col-md-4 col-md-offset-4 well' >
Incorrect <font color = '#de615e'> Username </font> or <font color = '#de615e'> Password </font>. Please try again
</div>";
}
}
?>
感谢您的时间
答案 0 :(得分:1)
我添加了“die”语句,在“Location”重定向后终止代码。这是因为用户基本上可以忽略重定向,如果你有一些可执行代码,它会留下潜在的错误
关于usertypes以及它们应该重定向到什么的重要事情是在switch语句中
if(isset($_SESSION['user_type']) && $_SESSION['user_type'] == "S") {
header("Location: /main/studenthome.php");
die();
}
else if(isset($_SESSION['user_type']) && $_SESSION['user_type'] == "A") {
header("Location: /main/staffhome.php");
die();
}
include_once 'dbconnect.php';
//check if form is submitted
if (isset($_POST['login'])) {
$username = mysqli_real_escape_string($con, $_POST['username']);
$password = mysqli_real_escape_string($con, $_POST['password']);
$result = mysqli_query($con, "SELECT * FROM users WHERE username = '" . $username. "' and password = '" . md5($password) . "'");
if ($row = mysqli_fetch_array($result)) {
$_SESSION['usr_id'] = $row['usrId'];
$_SESSION['usr_name'] = $row['username'];
$_SESSION['user_type'] = $row["usertype"];
switch ($_SESSION['user_type']) {
case 'Student':
header("Location: /main/studenthome.php");
break;
case 'Teacher':
header("Location: /main/anotherplace.php");
break;
}
die();
} else {
echo "<div class= 'col-md-4 col-md-offset-4 well' >
Incorrect <font color = '#de615e'> Username </font> or <font color = '#de615e'> Password </font>. Please try again
</div>";
}
}
?>