PHP中的管理员和用户权限

时间:2019-04-22 14:04:52

标签: php

因此,我正在建立自己的网站,并且还在php代码中新增了即时消息,只是我刚开始时遇到了一个问题,即如何禁用具有“用户”角色的用户,并且只能使用“管理员”来访问“管理员”页面角色可以访问和使用它。这个问题我的PHP代码将是什么?我看到了一些代码,但是我在理解它时确实遇到了问题,因为我是PHP代码中的新手。

这是我在问题中使用的代码

server.php

if (mysqli_num_rows($results) == 1) { // user found
            // check if user is admin or user
            $logged_in_user = mysqli_fetch_assoc($results);
            if ($logged_in_user['user_type'] == 'admin') {

                $_SESSION['user'] = $logged_in_user;
                $_SESSION['success']  = "You are now logged in";
                header('location: admin/home.php');       
            }else{
                $_SESSION['user'] = $logged_in_user;
                $_SESSION['success']  = "You are now logged in";

                header('location: index.php');
            }

但是用户角色仍然能够访问admin / home.php

在admin / home.php中我也有此代码

home.php

if (!isLoggedIn()) {
    $_SESSION['msg'] = "You must log in first";
    header('location: ../errors-404.html');
}

这是isLoggedIn的功能

function isLoggedIn()
{
    if (isset($_SESSION['user'])) {
        return true;
    }else{
        return false;
    }
}

3 个答案:

答案 0 :(得分:2)

您可以在isLoggedIn()功能中添加用户类型检查:

function isLoggedIn($type = null)
{
    if (!isset($_SESSION['user'])) {
        // We got no session at all. Not logged in.
        return false;
    }

    $currentType = $_SESSION['user']['user_type'] ?? null;

    if ($type && $type != $currentType) {
        // We got a type passed to the function, but the session type
        // doesn't match
        return false;
    }

    // Either we got no type or the type matched.
    return true;
}

现在,您可以使用它来检查用户是否完全登录(通过省略参数)或用户是否具有特定角色(通过将角色传递给函数):

要检查用户是否完全登录:

// In the top of the page you want to protect
if (!isLoggedIn()) {
    // Not logged in at all
    header('location: foo.php');
    exit;
}

要检查用户是否以特定角色登录:

// In the top of the page you want to protect
if (!isLoggedIn('admin')) {
    // Not logged in as an admin
    header('location: bar.php');
    exit;
}

答案 1 :(得分:1)

因为您只是检查$_SESSION['user']是否已设置,并且在两种情况下都已设置。

检查为:

function isAdmin()
{
  //this checks is user is logged in and type == "admin" 
 return (isset($_SESSION['user']) &&   isset($_SESSION['user_type']) && ($_SESSION['user_type']=="admin")  ); 

}

概念上应该有另一个类似的功能

function validateLogin(){

   if(isLoggedIn()){
     if(isAdmin()){
       //redirect to admin page
      } 
      else{
              //redirect to user page
      } 
   }
   else{
      // invalid login
   } 
}

在您的.php文件的管理员顶部,使用相同的功能来验证用户是否有权访问该特定页面。

答案 2 :(得分:0)

您需要在管理页面上更改以下功能。

function isLoggedIn()
{
    if (isset($_SESSION['user']) && $_SESSION['user']['user_type'] == 'admin') {
        return true;
    }else{
        return false;
    }
}
相关问题