php - 具有不同重定向的php登录页面
问题描述
我创建了链接到数据库的登录页面,我想根据用户角色将用户重定向到不同的主页,如果 1 在登录后重定向到 indexorg.php 并且如果 0 在登录后重定向到 indexpart.php 但是它不起作用并且全部被重定向到代码中第一个 indexorg.php 或 indexpart.php 的同一页面
这是我的代码
<?php
// Initialize the session
session_start();
// Check if the user is already logged in, if yes then redirect him to welcome page
if(isset($_SESSION["loggedin"]) && $_SESSION["loggedin"] === true){
if ($_SESSION["user_role"] = "1") {
$redirect = 'indexorg.php';
} else if ($_SESSION["user_role"] == "0") {
$redirect = 'indexpart.php';
}
header('Location: ' . $redirect);
//header("location: index.php");
exit;
}
// Include config file
require "config.php";
// Define variables and initialize with empty values
$email = $password = "";
$email_err = $password_err = "";
// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
// Check if email is empty
if(empty(trim($_POST["email"]))){
$email_err = "Please enter email.";
} else{
$email = trim($_POST["email"]);
}
// Check if pass is empty
if(empty(trim($_POST["password"]))){
$password_err = "Please enter your password.";
} else{
$password = trim($_POST["password"]);
}
// Validate credentials
if(empty($email_err) && empty($password_err)){
// Prepare a select statement
$sql = "SELECT user_role, user_id, email, password FROM users WHERE email = :email";
if($stmt = $pdo->prepare($sql)){
// Bind variables to the prepared statement as parameters
$stmt->bindParam(":email", $param_email, PDO::PARAM_STR);
// Set parameters
$param_email = trim($_POST["email"]);
// Attempt to execute the prepared statement
if($stmt->execute()){
// Check if email exists, if yes then verify password
if($stmt->rowCount() == 1){
if($row = $stmt->fetch()){
$id = $row["user_id"];
$email = $row["email"];
$hashed_password = $row["password"];
$role = intval($row['user_role']);
if(password_verify($password, $hashed_password)){
// Password is correct, so start a new session
session_start();
// Store data in session variables
$_SESSION["loggedin"] = true;
$_SESSION["user_id"] = $id;
$_SESSION["email"] = $email;
$_SESSION["user_role"] == $role;
// if ($role=1) {
// $redirect = 'indexorg.php';
// } else if ($role= 0) {
// $redirect = 'indexpart.php';
// }
switch ($role) {
case 0:
$redirect= "indexpart.php";
break;
case 1:
$redirect= "indexpart.php";
break;
}
header('Location: ' . $redirect);
exit();
// Redirect user to welcome page
//header("location: index.php");
} else{
// Display an error message if password is not valid
$password_err = "The password you entered was not valid.";
}
}
} else{
// Display an error message if email doesn't exist
$email_err = "No account found with that email.";
}
} else{
echo "Oops! Something went wrong. Please try again later.";
}
// Close statement
unset($stmt);
}
}
// Close connection
unset($pdo);
}
?>
解决方案
在这一行
if ($_SESSION["user_role"] = "1")
您实际上将“1”分配给 $_SESSION["user_role"] 这始终是正确的。
为了进行比较,您应该使用==
或!=
在第二次比较中使用。