Multi User Role Based Login System Using Bootstrap 5, PHP & MySQL

3 min read 2 hours ago
Published on Oct 07, 2024 This response is partially generated with the help of AI. It may contain inaccuracies.

Table of Contents

Introduction

In this tutorial, we will build a multi-user role-based login system using Bootstrap 5, PHP, and MySQL. This system will allow different user roles to log in and access specific functionalities based on their permissions. By the end of this guide, you’ll have a robust authentication system ready for your web application.

Step 1: Set Up Your Development Environment

  • Install a local server environment such as XAMPP or WAMP.
  • Download and install Bootstrap 5. You can include Bootstrap via CDN in your HTML files.
  • Create a new project folder in your server’s root directory (e.g., htdocs for XAMPP).

Step 2: Create the Database and Tables

  1. Open PHPMyAdmin and create a new database named user_roles.
  2. Create the following tables within the user_roles database:
    • users: to store user information.
      CREATE TABLE users (
          id INT(11) AUTO_INCREMENT PRIMARY KEY,
          username VARCHAR(50) NOT NULL,
          password VARCHAR(255) NOT NULL,
          role ENUM('admin', 'editor', 'viewer') NOT NULL
      );
      
    • Insert sample users into the users table:
      INSERT INTO users (username, password, role) VALUES
      ('admin', '$2y$10$somehashedpassword', 'admin'),
      ('editor', '$2y$10$somehashedpassword', 'editor'),
      ('viewer', '$2y$10$somehashedpassword', 'viewer');
      
    • Ensure passwords are hashed using PHP's password_hash() function.

Step 3: Build the Login Form

  • Create an index.php file in your project folder.
  • Include the Bootstrap 5 CDN link in the <head> section.
  • Add the following HTML code to create the login form:
    <form method="POST" action="login.php">
        <div class="form-group">
            <label for="username">Username</label>
            <input type="text" class="form-control" name="username" required>
        </div>
        <div class="form-group">
            <label for="password">Password</label>
            <input type="password" class="form-control" name="password" required>
        </div>
        <button type="submit" class="btn btn-primary">Login</button>
    </form>
    

Step 4: Handle Login Logic

  • Create a login.php file to process the login form submission.
  • Use the following code snippet to handle the login logic:
    session_start();
    include 'db_connection.php'; // Connect to the database
    
    if ($_SERVER["REQUEST_METHOD"] == "POST") {
        $username = $_POST['username'];
        $password = $_POST['password'];
    
        $stmt = $conn->prepare("SELECT * FROM users WHERE username = ?");
        $stmt->bind_param("s", $username);
        $stmt->execute();
        $result = $stmt->get_result();
    
        if ($result->num_rows > 0) {
            $user = $result->fetch_assoc();
            if (password_verify($password, $user['password'])) {
                $_SESSION['username'] = $username;
                $_SESSION['role'] = $user['role'];
                header("Location: dashboard.php");
            } else {
                echo "Invalid password.";
            }
        } else {
            echo "No user found.";
        }
    }
    

Step 5: Create a Dashboard

  • Create a dashboard.php file that checks the user’s role and displays content accordingly:
    session_start();
    if (!isset($_SESSION['username'])) {
        header("Location: index.php");
        exit();
    }
    
    echo "Welcome, " . $_SESSION['username'] . "!";
    if ($_SESSION['role'] == 'admin') {
        echo "You have admin privileges.";
    } elseif ($_SESSION['role'] == 'editor') {
        echo "You can edit content.";
    } else {
        echo "You can view content.";
    }
    

Conclusion

You have successfully built a multi-user role-based login system with PHP, MySQL, and Bootstrap 5. This system allows users to log in and access different functionalities based on their roles. As next steps, consider enhancing user registration, improving security, and expanding user role management. For additional resources, check the source code here. Happy coding!