Multiple administrators login with PHP

Giorgio

I am trying to create a PHP website with more than one administrator. I have some doubts

  1. How can I check if an admin is logged in? I know I must use sessions for security reasons, but how can I recognize which one of the administrators is logged in?

  2. Should I set a $_SESSION['username'] variable when username performs login and send a cookie containing username too? This way, I know who is him (or pretends to be) and can check if username is actually logged in, checking $_SESSION['username'] before showing pages. Is it secure?

Royal Bg

How can I check if an admin is logged in? I know I must use sessions for security reasons, but how can I recognize which one of the administrators is logged in?

Same way as you check if a normal user is logged in. A session, ofcourse. Both, normal user and administrator should have $_SESSION['username'] set in. To make someone administrator, I guess, you are using a flag in the db, let's say the column is access_level. ENUMs are 1 => user, 2 => adminitrator. So when you login the user, put into session this one too. $_SESSION['access_level'] will tell you if this user is admin, and $_SESSION['username'] will tell you its username.

Should I set a $_SESSION['username'] variable when username performs login and send a cookie containing username too? This way, I know who is him (or pretends to be) and can check if username is actually logged in, checking $_SESSION['username'] before showing pages. Is it secure?

Sessions are enough. They do set cookies on client site aswell. Do not store additional $_COOKIE['username'].

I am using a MVC structure, so I would like to build something (a model, a controller) to use it also for login / check credentials / logout operations. Which is the most elegant (object oriented) way to achieve it?

In a few words - a model method for login. If user is admin, normal, etc, could be done by the controller by using the extract of the model, which queries the DB taking username, password, access_level, etc.

const USER_NORMAL = 1;
const USER_ADMIN = 2;

public function isAdmin() {
    $row = $this->_application->UserModel->login();
    if($row['access_level'] == self::USER_ADMIN) {
        return true;
    }
    return false;
}

I have some scripts (i.e. a "upload.php" script, to let admins to upload files) which can be only accessed if one of the admins is logged in. These scripts are not views, so I can't check login (my intention was to check login on controller level, before showing pages). So how can I do in this case?

So check on controller as you wish, with the method above.

if(!$this->UserController->isAdmin()) {
    header("Location: index.php");
}
else {
   // show page
}

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related