PHP登录然后重定向


PHP login then redirect

我使用以下代码将用户登录到一系列安全页面-提交后,我需要将每个用户重定向到适当的页面,我想知道我需要采取哪些步骤来区分三个登录级别(admin、special、user):

if(isset($_SESSION['username'])){
    function check_login($level) {
        $username_s = mysql_real_escape_string($_SESSION['username']); 
        $sql = "SELECT user_level, restricted FROM login_users WHERE username = '$username_s'"; 
        $result = mysql_query($sql);
        $row = mysql_fetch_array($result);
        $user_level = $row['user_level'];
        $restricted = $row['restricted'];
        $sql = "SELECT level_disabled FROM login_levels WHERE level_level = '$user_level'"; 
        $result = mysql_query($sql);
        $row2 = mysql_fetch_array($result);
        $disabled = $row['level_disabled'];
        if($disabled != 0) { include('disabled.php'); exit();
        } elseif($restricted != 0) { include('disabled.php'); exit();
        } elseif($user_level <= $level) { // User has authority to view this page.      
        } else { include('user_level.php'); exit();
        }
    }
} else {
    function check_login($level) { exit(); }
    include('login.inc.php'); exit();

我会将登录级别存储在$_SESSION变量中,然后根据该变量重定向用户,因为您需要逐页跟踪该登录级别。要重定向它们,请使用带有Location:字符串的header()。

例如:

if ($_SESSION['log_level'] == 'admin') {
   header("Location: admin.php");
} else if ($_SESSION['log_level'] == 'editor') {
   header("Location: editor.php");
} else if ($_SESSION['log_level'] == 'author') {
   header("Location: author.php");
}

我会将这些函数调用从if语句中移出,并将其保留在其他地方。。。

一种方法可以是在数组中声明您喜欢的不同级别:$levels = array('admin' => '/admin/url', 'special' => '/special/url', 'guest' => '/guest/url');,然后遍历列表,或者查看键是否存在。。。

使用switch是另一种方法。。。

if (isset($_SESSION['login_level'])) { 
      switch ($_SESSION['login_level']) {
          case 'admin': 
               header('Location: /admin/url');
               break;
          case 'special':
               header('Location: /special/url');
               break;
          case 'guest':
               header('Location: /guest/url');
               break;
          default:
               do_login();
               break;
       }
  } else { 
      do_login();
  }
 function do_login() {
     // do something
 }