检查php中的用户权限

时间:2013-05-05 12:58:36

标签: php class function admin-rights

如何创建一个PHP函数或类来检查半管理员(从MySQL数据库设置)的用户是否具有创建新页面,编辑或删除等权限? 我需要一个检查用户权限的函数,然后显示如下代码:

  if ($he_can_create_page){
  //continue the script.....
  }else{
  //don`t continue
   }

目前我使用这样的会议:

    If($_SESSION['user_type']=='Admin'||$_SESSION['user_type']=='premium'){
 //do stuff
 }else if()......... {
  // ..............
   }

但如果语句变得太多,我想要一个更干净的代码:)

4 个答案:

答案 0 :(得分:3)

interface User {

    public function canCreatePage();
    public function canDeletePage();
    public function canEditPage();
    ....
}

class Admin implements User {

    public function canCreatePage(){
        return true;
    }

    public function canEditPage(){
        return true;
    }
    ...
}

class Editor implements User {

     public function canCreatePage() {
          return false;
     }

     public function canEditPage(){
        return true;
     }

     ...

}

然后从数据库中得到的内容

if ($row['user_type'] == 'Admin') {
   $user = new Admin();
} else if $row['user_type'] == 'Editor') {
   $user = new Editor();
}  ....

在您的所有网页中:

if ($user->canCreatePage()){
  //continue the script.....
}else{
  //don`t continue
}

如果您希望在第一次从dataBase

获取用户时将用户存储在会话中
$_SESSION['user'] = serialize($user);

在下一页

$user = unserialize($_SESSION['user']);

或者您也可以将用户的ID存储在会话中并从de中获取 每页都有数据库。

答案 1 :(得分:0)

在您的用户表格中添加列,如:

| canEdit | canDelete | canCreate |

带有标志1/0。 1表示真,0表示假。

选择字段并进行检查,即:

if($row['canEdit'] = 1) {
//continue (return true)
}
else {
//stop (return false)
}

您可以使用params使其成为函数,因此您将为该函数提供参数,即$ canDelete(这是您的$ row数据)并且它仅检查该权限

function userPermissions($type)
 if($type=1) {
   return true;
 }
 else {
   return false;
 }


$canCreate = $row['canCreate'];

if(userPermissions($canCreate)) { ...

答案 2 :(得分:0)

创建一个通用函数并将其放在一个文件中,这个文件对于所有类似的文件都是通用的

 function pageCreatePermission() {
     if($_SESSION['user_type']=='Admin'||$_SESSION['user_type']=='premium'){

          return true;

     } else { 
          return false;
}

然后在你的文件中使用这个函数

if (pageCreatePermission()) {
     //do your stuff
 } else {
     //show error you want
 }

答案 3 :(得分:0)

答案是使用门​​禁系统。有许多不同的类型。最常用(在Web开发中)是ACL(访问控制列表)和RBAC(基于角色的访问控制)。规则可以从数据库填充或硬编码。

为了让您了解它们的工作原理,请查看Zend Framework中的示例:ACLRBAC。 在Zend Framework中,ACL与RBAC没有太大区别,因为它也有角色。但通常ACL是基于用户而不是基于角色的。如果您愿意,可以将Zend或其他框架中的ACL / RBAC集成到您自己的项目中。

了解yii如何做到:yii RBAC

相关问题