登录后,根据用户角色重定向到不同的页面


After login redirect to different page according to user role

我想修改我的代码以在登录后根据用户角色重定向到不同的页面,无论角色如何,我都只能进行一次通用重定向。我需要有关如何实现的帮助。

这是我的用户数据库表:

userID  fullname    email               role    password
1       Tester one  test@gmail.com      N       ALSJALDDJ6464!JJLSK
2       Tester two  tester@gmail.com    C       @ALSJAL5656DDJJJLSK

我的PHP登录代码在这里:

<?php
error_reporting(E_ALL ^ E_NOTICE);
ini_set('display_errors', 1);
// establishing the MySQLi connection
// Create connection
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "timewise";
$conn = new mysqli($localhost, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 
// checking the user
if(isset($_POST['btnLogin'])){
$email = mysqli_real_escape_string($conn,$_POST['uemail']);
$pass = mysqli_real_escape_string($conn,$_POST['upass']);
//$pass = crypt($pass);

$sel_user = "SELECT * FROM users WHERE email='$email' AND pass='$pass'";
$run_user = mysqli_query($conn, $sel_user);
if (!$sel_user) {
die(mysqli_error($conn));
}
$check_user = mysqli_num_rows($run_user);
if($check_user>0){
$user_data = mysqli_fetch_assoc($run_user);
if ($user_data["role"] == 'C') {
    //redirect somehwere
    print '<script type="text/javascript">window.location = "index.html"</script>';
} else {
    //redirect somehwere else
    print '<script type="text/javascript">window.location = "form-wizard.html"</script>';
}
} else {
    // more code here
    echo '<center><span style="color:#801b1b; border:1px solid #e5a3a3; background:#ffcfcf; padding:5px;">Email or password is not correct, please try again!</span></center>';
}
}
?>

我需要有关根据角色将登录用户重定向到不同页面的帮助,即

"

N"表示普通用户,"C"表示公司用户。

那么,让我们开始:

$sel_user = "SELECT * FROM users WHERE email='$email' AND pass='$pass'";
$run_user = mysqli_query($conn, $sel_user);
// this will never happens as $sel_user is a string and it's not empty
// I suppose you need to check `$run_user`
if (!$sel_user) {
    die(mysqli_error($conn));
} 
$check_user = mysqli_num_rows($run_user);
if($check_user>0){
    // here you need $run_user data
    // use fetch_ methods, for example `fetch_assoc()`
    $user_data = mysqli_fetch_assoc($run_user);
    // print_r($user_data) to check keys
    if ($user_data["role"] == 'C') {
        //redirect somehwere
    } else {
        //redirect somehwere else
    }
} else {
    // more code here
}

您可以使用header('location: /file')函数根据用户在某些if/else中的位置立即重定向到不同的页面,或者将链接作为变量,这将是header("location: " . $file)。我希望这是有帮助的!