基于角色php的登录重定向


Login redirection based on role php

我有一个登录数据库

username | password | role
xxxxxx     xxxxxxx    Admin
xxxxxx     xxxxxxx    Trainer
xxxxxx     xxxxxxx    Client
xxxxxx     xxxxxxx    Line Manager

是否有可能在登录时,具有管理员角色的人重定向到Admin.php具有培训师角色的人登录到Trainer.php具有客户端角色的人登陆到Client.php。

假设您已经从数据库中检索到用户信息,并将他们的角色存储到Session变量中,那么就这么简单。。。

<?php
 session_start();
 $role = $_SESSION['role'];
 if($role=="Admin"){header("location: www.yourpage.com/admin.php");}
 elseif($role=="Trainer"){header("location: www.yourpage.com/trainer.php");}
 elseif($role=="Client"){header("location: www.yourpage.com/client.php");}

简短回答:是。

您可以从数据库中为用户检查角色,然后可以使用开关或if结构进行重定向:

 switch ($role) {
     case 'admin':
         $_SESSION['role'] = 'admin';
         // redirect to admin
         header( 'Location: admin.php');
         break;
     case 'client':
         $_SESSION['role'] = 'client';
          // redirect to client
         header( 'Location: client.php');
         break;
      case 'trainer':
         $_SESSION['role'] = 'trainer';
          // redirect to admin
         header( 'Location: trainer.php');
         break; }

$_SESSION var允许您检查访问admin.php、client.php或trainer.php的用户是否真的是经过身份验证的管理员/客户端/培训师。

首先获取有效用户的角色,并像以下一样进行比较

 $Role  = query_database("SELECT * FROM YOUR_TABLE_NAME WHERE username='".$_POST["username"]."'");

if ( $Role == "Admin")
 {
    header("location:www.example.com/admin.php");
 }
  else  if ( $Role == "Trainer ")
 {
          header("location: www.example.com/Trainer.php");
 }

像这个

当然,只需存储角色->家庭关系并查找它,类似

<?php
function get_home_by_role($role)
{
    $home = 'admin.php';
    $roles = array(
        'client'    => 'client.php',
        'trainer'   => 'trainer.php',
    );
    if (isset($roles[$role])) {
        $home = $roles[$role];
    }
    return $home;
}
$user = get_user();
$home = get_home_by_role($user->role);
header("Location: http://example.org/$home");
exit;

安东尼。

假设您的登录表名为users,则您已经连接到数据库,并且用户在填写某种登录表单后加载此页面:

$q = "SELECT * FROM users WHERE username='".$_POST["username"]."'";
$result = mysql_query($q) or die(mysql_error());
$row = mysql_fetch_array($result);
switch($row["role"])
{
    case "Admin":
       header("Location: http://".$_SERVER['SERVER_NAME']."/admin.php");
       die();
       break;
    case "Trainer":
    //.....
}

我会使用这样的东西(但可能使用数据库表来存储角色重定向,使其更动态):

$redirect = array(
    'Admin' => 'http://example.com/admin.php',
    'Trainer' => 'http://example.com/trainer.php',
    'Client' => 'http://example.com/client.php',
    //...
    );
if ($redir = @$redirect[$role]) {
    header('Location: ' . $redir);
    ob_end_clean(); // In case you've had output buffered already; optional.
    exit();
}
else
    die("Unknown role: $role; don't know where to go!");