get_user_level()
public function get_user_level(?string $token = null): string|bool
Description
Retrieves the user level (title) associated with a token. If no token is provided, checks session, cookie, and HTTP headers automatically.
User levels are string values stored in the user_level column of the user table (e.g., 'admin', 'member', 'guest').
Parameters
| Parameter | Type | Description | Default | Required |
|---|---|---|---|---|
| $token | string|null | A 64‑character hexadecimal token. If null, the method searches session, cookie, and HTTP headers. | null | No |
Return Value
| Type | Description |
|---|---|
| string|bool |
|
Example Usage
PHP
// Get current user's level
$level = $this->trongate_tokens->get_user_level();
if ($level !== false) {
echo "User level: " . $level;
}
// Check if user is admin
public function admin_area() {
$level = $this->trongate_tokens->get_user_level();
if ($level !== 'admin') {
redirect('members/not_allowed');
}
// Show admin content...
}
// Role‑based access control
public function edit_post(int $post_id) {
$level = $this->trongate_tokens->get_user_level();
$post = $this->model->get_post($post_id);
if ($level === 'admin' || ($level === 'editor' && $post->author_id === $this->trongate_tokens->get_user_id())) {
// Allow edit
} else {
redirect('posts/view/' . $post_id);
}
}
// API endpoint for admins only
public function delete_user(int $user_id) {
if ($this->trongate_tokens->get_user_level() !== 'admin') {
http_response_code(403);
echo json_encode(['error' => 'Forbidden']);
die();
}
// Delete user...
}Notes
- Internally calls
get_user_obj()to retrieve the full user object, then extracts theuser_levelproperty. - Token search order when
$tokenis null: HTTP header → cookie → session. - Returns
falseif token is expired, invalid, or not found. - User level is a string; for integer‑based levels, you may need to cast or use a different approach.
- The
user_levelcolumn must exist in your user table (default:trongate_users).