Role-based security checks (RBAC) ni mechanism ya ku-restrict access kulingana na user role.

Mfano wa roles:

Admin – full access

Editor – edit content

User – view-only

Goal: Ensure each user only accesses pages na functionalities wanaoruhusiwa.

⚙️ 2. Database Structure Example
CREATE TABLE roles (
id INT AUTO_INCREMENT PRIMARY KEY,
role_name VARCHAR(50) NOT NULL UNIQUE
);

CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50) NOT NULL UNIQUE,
password VARCHAR(255) NOT NULL,
role_id INT NOT NULL,
FOREIGN KEY (role_id) REFERENCES roles(id)
);

INSERT INTO roles (role_name) VALUES ('Admin'), ('Editor'), ('User');

🧩 3. Login Example with Role Assignment
<?php
session_start();
$pdo = new PDO("mysql:host=localhost;dbname=multi_user_system;charset=utf8mb4","root","");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

if(isset($_POST['login'])){
$username = htmlspecialchars(trim($_POST['username']));
$password = $_POST['password'];

$stmt = $pdo->prepare("SELECT u.*, r.role_name FROM users u JOIN roles r ON u.role_id = r.id WHERE username=:username");
$stmt->execute(['username'=>$username]);
$user = $stmt->fetch();

if($user && password_verify($password, $user['password'])){
session_regenerate_id(true);
$_SESSION['user_id'] = $user['id'];
$_SESSION['username'] = $user['username'];
$_SESSION['role'] = $user['role_name'];
echo "✅ Login successful! Role: ".$_SESSION['role'];
} else {
echo "❌ Invalid credentials!";
}
}
?>

🧩 4. Role-Based Access Check on Protected Pages
<?php
session_start();

// Ensure user is logged in
if(!isset($_SESSION['user_id'])){
header("Location: login.php");
exit();
}

// Admin-only page
if($_SESSION['role'] !== 'Admin'){
die("❌ Access denied. Admins only.");
}

// Editor or Admin page
if(!in_array($_SESSION['role'], ['Admin','Editor'])){
die("❌ Access denied. Admins or Editors only.");
}

// Page content for allowed roles
echo "Welcome ".$_SESSION['username']."! You have access to this page.";
?>


💡 Maelezo:

Use $_SESSION['role'] to check permissions.

in_array() allows multiple roles access.

Restrict sensitive pages/functions early to prevent unauthorized access.

🔑 5. Best Practices

Always check roles server-side – never rely on client-side checks.

Use sessions securely – regenerate session ID, secure cookies, enforce HTTPS.

Centralize access checks – use functions or middleware for reusable security.

Least privilege principle – give users minimum permissions necessary.

Audit roles and permissions regularly – remove unnecessary privileges.

✅ 6. Hitimisho

Role-based security checks ni critical for multi-user applications.

Prevents unauthorized access and enforces least privilege principle.

Can be combined with CSRF tokens, input validation, login attempt limiter for maximum security.

🔗 Tembelea:

👉 https://www.faulink.com/

Kwa mafunzo zaidi ya PHP, multi-user security, na best practices za web applications.