我一直在努力,想知道如何让我的登录表单根据用户类型重定向用户。我有客户和管理员作为数据库中的用户类型。我的代码包括登录页面,登录控制器,数据访问页面,用户类页面和注销。
登录页面
<?php require_once ("../Controller/loginController.php"); ?>
<form action="" method= "POST">
<br><br>
Username:
<input name="loginName" placeholder="User Name">
<br><br><br>
Password:
<input type="password" name="loginPassword" placeholder="Password">
<br><br>
<input type="submit" value="Log In" name="button"> <span style="color: red"><?='<br><br>'. $error?></span>
</form>
登录控制器页面
<?php
require_once("../Model/dataAccess.php");
require_once("../Model/user.class.php");
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
if (!isset($error)) {
$error = "";
}
if (isset($_SESSION["loggedInUser"])) {
header('Location: ../View/account.php');
die();
} else if (isset($_REQUEST["button"])) {
$username = !empty($_REQUEST["loginName"]) ? trim($_REQUEST["loginName"]) : null;
$password = !empty($_REQUEST["loginPassword"]) ? trim($_REQUEST["loginPassword"]) : null;
$currentuser = getLogIn($username, $password);
if ($currentuser) {
$_SESSION["loggedInUser"] = $currentuser;
$error = "You have logged in successfully";
header('Location: ../View/account.php');
die();
}
else {
$error = "The login details supplied do not match any valid user.";
header('Location: ../View/login.php');
}
}
?>
退出页面
<?php
session_start();
unset($_SESSION["loggedInUser"]);
session_destroy();
$error = "You have successfully logged out.";
echo $error . '<br><br>';
echo 'Click <a href="login.php">here</a> to login.';
?>
数据访问页
<?php
require_once('../Model/user.class.php');
function getLogIn($username, $password)
{
global $pdo;
$sqlUserLog = 'SELECT userType FROM User WHERE userName= ? AND userPass= ?';
$stmtUserLog = $pdo->prepare($sqlUserLog);
if (!$stmtUserLog->execute(array(
$username,
$password
))) {
die('Error');
}
$UserLog = $stmtUserLog->fetch();
return $UserLog;
}
?>
用户类页面
<?php
class User
{
var $userID;
var $userType;
var $userName;
var $userPass;
function __get($name)
{
return $this->$name;
}
function __set($name, $value)
{
$this->$name = $value;
}
}
?>
答案 0 :(得分:3)
if ($currentuser)
{
$_SESSION["loggedInUser"] = $currentuser;
// its a bad programming practice to set as "error" a success message
$error = "You have logged in successfully";
if($currentuser['userType'] == 'admin'){
header('Location: ../View/adminAccount.php');
}
else {
header('Location: ../View/account.php');
}
die();
}
另外请注意,以明文形式存储密码是一种不好的做法,我假设从这部分if(!$stmtUserLog->execute(array($username, $password))) {