This is how I go about doing it, in my utilities.inc.php (configuration file that I put on every page) I have this:
[php]/* Use $user for sessions variable */
$user = isset($_SESSION[‘user’]) ? $_SESSION[‘user’] : NULL;[/php]
When a User logs in I do this:
[php] public function read(array $data = NULL) {
$this->query = ‘SELECT id, username, password, security_level, first_name, last_name, email, home_phone, cell_phone, gender, birthday FROM users WHERE username=:username’;
$this->query_params = [’:username’ => $data[‘username’]];
try {
$this->stmt = $this->pdo->prepare($this->query);
$this->result = $this->stmt->execute($this->query_params);
} catch (Exception $ex) {
die("Failed to run query: " . $ex->getMessage());
}
$this->stmt->setFetchMode(PDO::FETCH_OBJ);
$this->user = $this->stmt->fetch();
if ($this->user) {
$this->loginStatus = password_verify($data['password'], $this->user->password);
unset($data['password']); // Unset the password:
unset($this->user->password);
}
if ($this->loginStatus) {
$_SESSION['user'] = $this->user; // Set the session variable of user:
return TRUE;
} else {
return FALSE;
}
}[/php]
Sorry, the above is written in OOP, but just think of it as a function and minus the $this-> part.
Then in my case I would just do something like the follow:
[php]if ($user && $user->security_level === “admin”) {
// Do something
} elseif ( $user && $user->“contributor”) {
// Do something else
}[/php]
If the if statements get unwieldy then you can just simply switch over to a switch statement. Just another way of doing it.