Search code examples
phpclassfunctionadmin-rights

Check user permission in php


How can I create a PHP function or class that checks if a user who is a half-admin (set from a MySQL database) has some rights such as creating a new page, editing, or deleting? I need a function that checks the user permissions and then display the code like this:

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

In present I use sessions like this:

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

but they become too many if statements, and I want a cleaner code :)


Solution

  • 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;
         }
    
         ...
    
    }
    

    then from what you get in the data base

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

    in all your pages :

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

    If you want to store your user in session the first time you get it from the dataBase

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

    in the next page

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

    Or you can also just store the id of the user in session and get it back from de DB on every page.