📲 Download Utility Tools Apps

EMI Calculator

Download EMI Calculator

SOA Games

Download SOA Games

SOA Technology App

Download SOA Technology

BMI Checker

Download BMI Checker

Task Jira

Download Task Jira

Laughing Adda

Download Laughing Adda

📅 हिंदी कैलेंडर ऐप डाउनलोड करें

Download Shubhcalendar App

complete Admin/User Role-Based Authentication system

Your system is now upgraded with a complete Admin/User Role-Based Authentication system 🔐

Here’s how it works in simple terms:


🧠 Role System Logic

✅ 1. Roles in Database

Each user now has:

  • user → normal user
  • admin → full access

✅ 2. During Login

  • System checks role from DB
  • Stores in session:
$_SESSION['role'] = $row['role'];

✅ 3. Role-Based Redirect

if ($row['role'] === 'admin') {
header("Location: admin.php");
} else {
header("Location: dashboard.php");
}

✅ 4. Access Control

User Page:

if ($_SESSION['role'] !== 'user') {
die("Access Denied");
}

Admin Page:

if ($_SESSION['role'] !== 'admin') {
die("Access Denied");
}

🔐 What You Now Have

✅ Login system
✅ Session authentication
✅ Remember Me (cookies)
✅ Auto login
✅ Logout system
✅ Role-based access (Admin/User)


⚠️ Important Upgrade (Real Projects)

Right now:
👉 UI + logic in one file (for learning)

In real project, MUST separate:

config.php
auth.php
login.php
register.php
dashboard.php
admin.php
logout.php
<?php
// ================= CONFIG =================
$host = "localhost";
$user = "root";
$pass = "";
$db   = "test_db";

$conn = new mysqli($host, $user, $pass, $db);
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

session_start();

// ================= AUTO LOGIN (REMEMBER ME) =================
if (!isset($_SESSION['user']) && isset($_COOKIE['remember_token'])) {
    $token = $_COOKIE['remember_token'];

    $stmt = $conn->prepare("SELECT * FROM users WHERE remember_token=?");
    $stmt->bind_param("s", $token);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows > 0) {
        $row = $result->fetch_assoc();
        $_SESSION['user'] = $row['username'];
        $_SESSION['role'] = $row['role'];
    }
}

// ================= REGISTER =================
if (isset($_POST['register'])) {
    $username = $_POST['username'];
    $password = password_hash($_POST['password'], PASSWORD_DEFAULT);
    $role = 'user'; // default role

    $stmt = $conn->prepare("INSERT INTO users (username, password, role) VALUES (?, ?, ?)");
    $stmt->bind_param("sss", $username, $password, $role);

    if ($stmt->execute()) {
        echo "Registered successfully";
    } else {
        echo "Error";
    }
}

// ================= LOGIN =================
if (isset($_POST['login'])) {
    $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) {
        $row = $result->fetch_assoc();

        if (password_verify($password, $row['password'])) {
            session_regenerate_id(true);
            $_SESSION['user'] = $row['username'];
            $_SESSION['role'] = $row['role'];

            // REMEMBER ME
            if (isset($_POST['remember'])) {
                $token = bin2hex(random_bytes(32));

                $stmt = $conn->prepare("UPDATE users SET remember_token=? WHERE id=?");
                $stmt->bind_param("si", $token, $row['id']);
                $stmt->execute();

                setcookie("remember_token", $token, time() + (86400 * 30), "/", "", true, true);
            }

            // redirect based on role
            if ($row['role'] === 'admin') {
                header("Location: admin.php");
            } else {
                header("Location: dashboard.php");
            }
            exit();
        } else {
            echo "Invalid Password";
        }
    } else {
        echo "User not found";
    }
}

// ================= LOGOUT =================
if (isset($_GET['logout'])) {
    if (isset($_SESSION['user'])) {
        $stmt = $conn->prepare("UPDATE users SET remember_token=NULL WHERE username=?");
        $stmt->bind_param("s", $_SESSION['user']);
        $stmt->execute();
    }

    setcookie("remember_token", "", time() - 3600, "/");

    session_unset();
    session_destroy();

    header("Location: login.php");
    exit();
}
?>

<!-- ================= REGISTER ================= -->
<h2>Register</h2>
<form method="POST">
    <input type="text" name="username" placeholder="Username" required><br><br>
    <input type="password" name="password" placeholder="Password" required><br><br>
    <button name="register">Register</button>
</form>

<!-- ================= LOGIN ================= -->
<h2>Login</h2>
<form method="POST">
    <input type="text" name="username" placeholder="Username" required><br><br>
    <input type="password" name="password" placeholder="Password" required><br><br>
    <label>
        <input type="checkbox" name="remember"> Remember Me
    </label><br><br>
    <button name="login">Login</button>
</form>

<!-- ================= USER DASHBOARD ================= -->
<?php if (isset($_SESSION['user']) && $_SESSION['role'] === 'user'): ?>
    <h2>User Dashboard</h2>
    <p>Welcome <?php echo $_SESSION['user']; ?></p>
    <a href="?logout=true">Logout</a>
<?php endif; ?>

<!-- ================= ADMIN PANEL ================= -->
<?php if (isset($_SESSION['user']) && $_SESSION['role'] === 'admin'): ?>
    <h2>Admin Panel</h2>
    <p>Welcome Admin: <?php echo $_SESSION['user']; ?></p>
    <a href="?logout=true">Logout</a>
<?php endif; ?>

/* ================= DATABASE =================
ALTER TABLE users ADD role VARCHAR(20) DEFAULT 'user';
ALTER TABLE users ADD remember_token VARCHAR(255) DEFAULT NULL;

-- Make a user admin manually
UPDATE users SET role='admin' WHERE username='admin';
*/


AI Spiritual Tools & Interactive Experiences

Explore powerful AI-driven tools for daily guidance, spirituality, fun quizzes, and self-discovery.

Today’s Quote

Get inspiring daily quotes powered by AI to motivate and guide your day.

Explore Now

AI Tarot Card Reader

Reveal insights about your future, love, and career with AI tarot readings.

Read Tarot

Love Match Calculator

Check compatibility and love predictions using AI-based analysis.

Check Match

Fortune Cookie

Open an AI fortune cookie and receive wisdom, luck, and fun messages.

Open Cookie

Quiz Categories

Engage with knowledge-based and fun quizzes across multiple categories.

Start Quiz

Panchang Calendar

View daily Panchang, auspicious timings, tithi, nakshatra, and festivals.

View Panchang

Online Numerology

Discover your destiny number, life path, and numerology predictions.

Calculate Now

Spiritual Feeds

Stay connected with spiritual thoughts, mantras, and divine content.

View Feeds

Quiz Hub

Attempt trending quizzes on GK, spirituality, festivals, and more.

Explore Quizzes