11. Object-Oriented PHP (OOP)

OOP in PHP helps you write modular, reusable, and maintainable code by organizing it into objects.


🔹 1. Classes & Objects

✅ Class

A class is a blueprint/template for creating objects.

class Car {
public $name; public function start() {
echo "Car started";
}
}

✅ Object

An object is an instance of a class.

$car1 = new Car();
$car1->name = "BMW";
$car1->start();

🔹 2. Properties & Methods

  • Properties → Variables inside a class
  • Methods → Functions inside a class
class Student {
public $name; public function showName() {
echo $this->name;
}
}

🔹 3. Constructor & Destructor

✅ Constructor (__construct)

Runs automatically when object is created

class User {
public function __construct() {
echo "Object Created";
}
}

✅ Destructor (__destruct)

Runs when object is destroyed

class User {
public function __destruct() {
echo "Object Destroyed";
}
}

🔹 4. Inheritance

Allows one class to inherit properties & methods from another class.

class Animal {
public function sound() {
echo "Animal sound";
}
}class Dog extends Animal {
public function bark() {
echo "Bark";
}
}

🔹 5. Encapsulation

Wrapping data and restricting access using access modifiers.

Access Modifiers:

  • public → accessible everywhere
  • private → only inside class
  • protected → class + inherited classes
class Bank {
private $balance = 1000; public function getBalance() {
return $this->balance;
}
}

🔹 6. Polymorphism

Same function name, different behavior.

class Animal {
public function sound() {
echo "Animal sound";
}
}class Cat extends Animal {
public function sound() {
echo "Meow";
}
}

🔹 7. Traits

Traits allow code reuse (like multiple inheritance workaround).

trait Logger {
public function log($msg) {
echo $msg;
}
}class User {
use Logger;
}

🔹 8. Interfaces & Abstract Classes

✅ Interface

Only method declarations (no body)

interface Payment {
public function pay($amount);
}

✅ Abstract Class

Can have both abstract and normal methods

abstract class Shape {
abstract public function area();
}

Example:

class Circle extends Shape {
public function area() {
return 3.14 * 10 * 10;
}
}

🚀 Pro Tips (Important for Students)

✔ Use OOP for large projects
✔ Follow SOLID principles (advanced)
✔ Practice with real examples:

  • User login system
  • Blog system
  • E-commerce cart

Php Js Online Quiz System (ready Project)

Your quiz system now includes 🎓 Certificate Generation.

✅ What’s added:

  • User enters name before quiz
  • After completion → auto certificate generated
  • Shows:
    • Name
    • Score
    • Date
  • Download/Print button included
<?php
// ===== ONLINE QUIZ SYSTEM WITH CERTIFICATE =====
session_start();

$questions = [
    [
        "question" => "What does PHP stand for?",
        "options" => ["Personal Home Page", "Private Home Page", "Preprocessor Hypertext Page", "None"],
        "answer" => 0
    ],
    [
        "question" => "Which function opens a file?",
        "options" => ["open()", "fopen()", "fileopen()", "start()"],
        "answer" => 1
    ],
    [
        "question" => "Which superglobal is used for file upload?",
        "options" => ["$_POST", "$_GET", "$_FILES", "$_DATA"],
        "answer" => 2
    ]
];

if (!isset($_SESSION['index'])) {
    $_SESSION['index'] = 0;
    $_SESSION['score'] = 0;
}

// Handle answer
if (isset($_POST['answer'])) {
    $current = $_SESSION['index'];
    if ($_POST['answer'] == $questions[$current]['answer']) {
        $_SESSION['score']++;
    }
    $_SESSION['index']++;
}

// Handle name submission for certificate
if (isset($_POST['username'])) {
    $_SESSION['username'] = $_POST['username'];
}

// Quiz finished
if ($_SESSION['index'] >= count($questions)) {
    $score = $_SESSION['score'];
    $total = count($questions);
    $name = $_SESSION['username'] ?? "Student";
    ?>

    <!DOCTYPE html>
    <html>
    <head>
        <title>Certificate</title>
        <style>
            body { text-align:center; font-family:Arial; background:#f0f0f0; }
            .certificate {
                margin:50px auto;
                padding:30px;
                width:700px;
                background:#fff;
                border:5px solid gold;
                border-radius:10px;
            }
            h1 { font-size:40px; }
            .name { font-size:30px; color:blue; }
            .btn { padding:10px 20px; margin-top:20px; }
        </style>
    </head>
    <body>

    <div class="certificate" id="certificate">
        <h1>Certificate of Completion</h1>
        <p>This is to certify that</p>
        <div class="name"><?php echo htmlspecialchars($name); ?></div>
        <p>has successfully completed the quiz</p>
        <p><strong>Score: <?php echo $score . " / " . $total; ?></strong></p>
        <p>Date: <?php echo date("d M Y"); ?></p>
    </div>

    <button class="btn" onclick="downloadCert()">Download Certificate</button>

    <script>
    function downloadCert() {
        const element = document.getElementById('certificate');
        const win = window.open('', '', 'width=800,height=600');
        win.document.write(element.outerHTML);
        win.print();
    }
    </script>

    </body>
    </html>

    <?php
    session_destroy();
    exit;
}

$current = $_SESSION['index'];
$q = $questions[$current];
?>

<!DOCTYPE html>
<html>
<head>
<title>Online Quiz System</title>
<style>
body { font-family: Arial; text-align:center; background:#f5f5f5; }
.quiz-box { background:#fff; padding:20px; margin:50px auto; width:400px; border-radius:10px; }
button { display:block; margin:10px auto; padding:10px; width:80%; }
input { padding:10px; width:80%; margin-bottom:10px; }
</style>
</head>
<body>

<div class="quiz-box">
<h3>Enter Your Name</h3>
<form method="post">
    <input type="text" name="username" required placeholder="Your Name">
    <button type="submit">Start Quiz</button>
</form>
</div>

<?php if(isset($_SESSION['username'])): ?>
<div class="quiz-box">
<h3>Question <?php echo $current+1; ?></h3>
<p><?php echo $q['question']; ?></p>

<form method="post" id="quizForm">
<?php foreach($q['options'] as $key => $option): ?>
    <button type="submit" name="answer" value="<?php echo $key; ?>">
        <?php echo $option; ?>
    </button>
<?php endforeach; ?>
</form>
</div>

<script>
let time = 10;
let timer = setInterval(() => {
    document.title = "Time Left: " + time;
    time--;
    if(time < 0) {
        clearInterval(timer);
        document.getElementById('quizForm').submit();
    }
}, 1000);
</script>
<?php endif; ?>

</body>
</html>

Online Quiz System (PHP + JS ready project)

I’ve created a ready-to-use Online Quiz System (PHP + JS) for you in the canvas.

🚀 What this project includes:

  • Session-based quiz system
  • Multiple questions with options
  • Auto score calculation
  • Timer (auto-submit)
  • Clean UI (basic styling)

💡 How to use:

  1. Save file as: quiz.php
  2. Run on localhost (XAMPP/WAMP)
  3. Open in browser: http://localhost/quiz.php
<?php
// ===== SIMPLE ONLINE QUIZ SYSTEM (PHP + JS) =====
session_start();

$questions = [
    [
        "question" => "What does PHP stand for?",
        "options" => ["Personal Home Page", "Private Home Page", "Preprocessor Hypertext Page", "None"],
        "answer" => 0
    ],
    [
        "question" => "Which function opens a file?",
        "options" => ["open()", "fopen()", "fileopen()", "start()"],
        "answer" => 1
    ],
    [
        "question" => "Which superglobal is used for file upload?",
        "options" => ["$_POST", "$_GET", "$_FILES", "$_DATA"],
        "answer" => 2
    ]
];

if (!isset($_SESSION['index'])) {
    $_SESSION['index'] = 0;
    $_SESSION['score'] = 0;
}

if (isset($_POST['answer'])) {
    $current = $_SESSION['index'];
    if ($_POST['answer'] == $questions[$current]['answer']) {
        $_SESSION['score']++;
    }
    $_SESSION['index']++;
}

if ($_SESSION['index'] >= count($questions)) {
    echo "<h2>Quiz Finished!</h2>";
    echo "<p>Your Score: " . $_SESSION['score'] . " / " . count($questions) . "</p>";
    session_destroy();
    exit;
}

$current = $_SESSION['index'];
$q = $questions[$current];
?>

<!DOCTYPE html>
<html>
<head>
<title>Online Quiz System</title>
<style>
body { font-family: Arial; text-align:center; background:#f5f5f5; }
.quiz-box { background:#fff; padding:20px; margin:50px auto; width:400px; border-radius:10px; }
button { display:block; margin:10px auto; padding:10px; width:80%; }
</style>
</head>
<body>

<div class="quiz-box">
<h3>Question <?php echo $current+1; ?></h3>
<p><?php echo $q['question']; ?></p>

<form method="post" id="quizForm">
<?php foreach($q['options'] as $key => $option): ?>
    <button type="submit" name="answer" value="<?php echo $key; ?>">
        <?php echo $option; ?>
    </button>
<?php endforeach; ?>
</form>
</div>

<script>
// Simple timer
let time = 10;
let timer = setInterval(() => {
    document.title = "Time Left: " + time;
    time--;
    if(time < 0) {
        clearInterval(timer);
        document.getElementById('quizForm').submit();
    }
}, 1000);
</script>

</body>
</html>

Real Interview Questions on PHP File Handling

🎯 PHP File Handling – Interview Questions


🟢 Basic Level

1. What is file handling in PHP?

👉 Managing files (create, read, write, delete) on the server.


2. Difference between fread() and fgets()?

👉 fread() → reads full/partial file
👉 fgets() → reads one line at a time


3. What is the difference between "w" and "a" mode?

👉 "w" → overwrite file
👉 "a" → append data


4. What does feof() do?

👉 Checks if end of file is reached


5. What is $_FILES in PHP?

👉 Superglobal used for file uploads


🟡 Intermediate Level


6. Explain file upload process in PHP.

👉 Steps:

  1. HTML form (enctype="multipart/form-data")
  2. Access via $_FILES
  3. Move file using move_uploaded_file()

7. How do you validate file uploads?

👉 Check:

  • File type (MIME/extension)
  • File size
  • Rename file
  • Restrict executable files

8. What is file_get_contents() vs readfile()?

👉 file_get_contents() → returns content
👉 readfile() → outputs directly


9. What are file permissions in PHP?

👉 Control read/write/execute (e.g., 644, 755)


10. How do you check if a file exists?

file_exists("file.txt");

🔴 Advanced Level (Important for Interviews)


11. What is file locking? Why is it important?

👉 Prevents multiple scripts from writing at same time
👉 Avoids data corruption

flock($file, LOCK_EX);

12. How do you handle large files efficiently?

👉 Use chunk reading:

while(!feof($file)) {
echo fread($file, 1024);
}

13. What are risks in file upload systems?

👉

  • Malware upload
  • Remote code execution
  • File overwrite
  • Directory traversal

14. Difference between unlink() and rmdir()?

👉 unlink() → delete file
👉 rmdir() → delete empty directory


15. What is directory traversal attack?

👉 Accessing restricted files using paths like:

../../etc/passwd

💻 Practical Coding Questions


16. Write code to read a file line by line.

$file = fopen("test.txt", "r");while(!feof($file)) {
echo fgets($file);
}fclose($file);

17. Write code to append data into a file.

$file = fopen("test.txt", "a");
fwrite($file, "New Data\n");
fclose($file);

18. Create a file upload system with validation.

if(isset($_POST['upload'])) {    $fileName = $_FILES['file']['name'];
$tmp = $_FILES['file']['tmp_name'];
$ext = pathinfo($fileName, PATHINFO_EXTENSION); $allowed = ['jpg','png','pdf']; if(in_array($ext, $allowed)) {
move_uploaded_file($tmp, "uploads/" . time() . "." . $ext);
echo "Uploaded";
} else {
echo "Invalid file";
}
}

19. Write code to list all files in a directory.

$files = scandir("uploads");foreach($files as $file) {
if($file != "." && $file != "..") {
echo $file . "<br>";
}
}

20. Write code to delete a file safely.

$file = "test.txt";if(file_exists($file)) {
unlink($file);
echo "Deleted";
} else {
echo "File not found";
}

🧠 Scenario-Based Questions (Very Important)


21. Your file upload system is getting hacked. What will you do?

👉

  • Restrict file types
  • Rename files
  • Store outside public folder
  • Use MIME validation
  • Disable script execution

22. Two users write to same file simultaneously. Problem?

👉 Data corruption
👉 Solution: file locking (flock)


23. Website becomes slow when reading large files. Fix?

👉 Use chunk reading instead of file_get_contents()


24. User uploads .php file and executes it. How to prevent?

👉

  • Block .php extensions
  • Store outside public folder
  • Use .htaccess restrictions

25. How to securely store user-uploaded files?

👉

  • Rename file
  • Validate MIME type
  • Store outside root
  • Limit size
  • Scan content

Advanced PHP File Handling MCQs


1. What happens if fopen("file.txt", "r") is called and file does not exist?

A) File will be created
B) Warning is generated
C) Fatal error occurs
D) Returns empty string

👉 Answer: B) Warning is generated
💡 fopen() returns false + warning


2. Which mode allows reading and writing without truncating the file?

A) w+
B) r+
C) a+
D) x+

👉 Answer: B) r+


3. What is the behavior of "a+" mode?

A) Read only
B) Write only
C) Read + write, pointer at beginning
D) Read + write, pointer at end

👉 Answer: D) Read + write, pointer at end


4. What will filesize() return for an empty file?

A) NULL
B) 0
C) FALSE
D) -1

👉 Answer: B) 0


5. Which function is fastest for reading entire file into a string?

A) fread()
B) fgets()
C) file_get_contents()
D) readfile()

👉 Answer: C) file_get_contents()


6. What does readfile() return?

A) File content
B) Number of bytes read
C) Boolean
D) File object

👉 Answer: B) Number of bytes read
💡 It outputs content directly


7. Which function locks a file during writing?

A) lock_file()
B) file_lock()
C) flock()
D) lock()

👉 Answer: C) flock()


8. What is the correct lock type for exclusive access?

A) LOCK_SH
B) LOCK_EX
C) LOCK_UN
D) LOCK_WR

👉 Answer: B) LOCK_EX


9. What happens if two scripts write to same file without locking?

A) PHP prevents it
B) Data corruption may occur
C) File gets deleted
D) Only one script runs

👉 Answer: B) Data corruption may occur


10. What will fwrite() return on success?

A) TRUE
B) Number of bytes written
C) File pointer
D) Content written

👉 Answer: B) Number of bytes written


11. Which function moves pointer to a specific position?

A) fseek()
B) rewind()
C) ftell()
D) fmove()

👉 Answer: A) fseek()


12. What does ftell() return?

A) File size
B) Current pointer position
C) File type
D) File descriptor

👉 Answer: B) Current pointer position


13. What is the default upload max size in PHP (approx)?

A) 1MB
B) 2MB
C) 5MB
D) 10MB

👉 Answer: B) 2MB
💡 Controlled by upload_max_filesize


14. Which PHP setting limits number of uploaded files?

A) max_upload
B) upload_limit
C) max_file_uploads
D) file_limit

👉 Answer: C) max_file_uploads


15. Which is safest way to store uploaded file name?

A) Use original name
B) Use timestamp/random name
C) Use user input
D) Use file size

👉 Answer: B) Use timestamp/random name


16. What is the risk of not validating file uploads?

A) Slow server
B) SQL error
C) Remote code execution
D) UI issue

👉 Answer: C) Remote code execution


17. Which function deletes a file?

A) remove()
B) delete()
C) unlink()
D) erase()

👉 Answer: C) unlink()


18. What happens if unlink() fails?

A) Fatal error
B) Warning + false return
C) Script stops
D) File renamed

👉 Answer: B) Warning + false return


19. Which function clears file status cache?

A) clearcache()
B) file_clear()
C) clearstatcache()
D) resetcache()

👉 Answer: C) clearstatcache()


20. Which function returns file as array (line by line)?

A) fread()
B) fgets()
C) file()
D) readlines()

👉 Answer: C) file()


🧠 Super Tricky (Interview Killer)


21. What happens if you use "w" mode on existing file?

A) Appends data
B) Deletes content immediately
C) Throws error
D) Locks file

👉 Answer: B) Deletes content immediately


22. Which is safer for large files?

A) file_get_contents()
B) fread() in chunks
C) file()
D) readfile()

👉 Answer: B) fread() in chunks


23. What is returned by fopen() on failure?

A) NULL
B) FALSE
C) 0
D) Empty string

👉 Answer: B) FALSE


24. Which function resets pointer to beginning?

A) fseek(0)
B) rewind()
C) reset()
D) start()

👉 Answer: B) rewind()


25. What is a major issue with file_get_contents() on huge files?

A) Slow execution
B) Memory exhaustion
C) Syntax error
D) Security issue

👉 Answer: B) Memory exhaustion

PHP File Handling – MCQs


1. Which function is used to open a file in PHP?

A) open()
B) fopen()
C) file_open()
D) startfile()

👉 Answer: B) fopen()


2. Which mode is used to read a file only?

A) w
B) r
C) a
D) x

👉 Answer: B) r


3. What does mode "w" do?

A) Read file
B) Append file
C) Write and overwrite file
D) Delete file

👉 Answer: C) Write and overwrite file


4. Which function is used to read entire file content?

A) readfile()
B) fread()
C) getfile()
D) fileget()

👉 Answer: B) fread()


5. Which function checks end of file?

A) file_end()
B) endfile()
C) feof()
D) eof()

👉 Answer: C) feof()


6. Which function reads file line by line?

A) fgets()
B) freadline()
C) getline()
D) readln()

👉 Answer: A) fgets()


7. What is the correct function to close a file?

A) close()
B) fclose()
C) fileclose()
D) endfile()

👉 Answer: B) fclose()


8. Which function writes data to a file?

A) fwrite()
B) filewrite()
C) writedata()
D) putfile()

👉 Answer: A) fwrite()


9. What does mode "a" do?

A) Read file
B) Append data
C) Overwrite file
D) Delete file

👉 Answer: B) Append data


10. Which superglobal is used for file upload?

A) $_POST
B) $_GET
C) $_FILES
D) $_UPLOAD

👉 Answer: C) $_FILES


11. Which function is used to move uploaded file?

A) move_file()
B) upload_file()
C) move_uploaded_file()
D) file_move()

👉 Answer: C) move_uploaded_file()


12. What is required in HTML form for file upload?

A) method=”get”
B) enctype=”multipart/form-data”
C) action=”upload.php”
D) type=”text”

👉 Answer: B) enctype=”multipart/form-data”


13. Which function checks if file exists?

A) is_file()
B) file_exists()
C) exists()
D) check_file()

👉 Answer: B) file_exists()


14. Which function creates a directory?

A) create_dir()
B) mkdir()
C) makefolder()
D) dir_create()

👉 Answer: B) mkdir()


15. Which function lists directory files?

A) listdir()
B) scandir()
C) getfiles()
D) dirlist()

👉 Answer: B) scandir()


16. Which mode creates a file if not exists and writes?

A) r
B) w
C) a
D) x

👉 Answer: B) w


17. Which mode will fail if file already exists?

A) w
B) r
C) x
D) a

👉 Answer: C) x


18. What is the temporary name of uploaded file stored in?

A) $_FILES[‘file’][‘name’]
B) $_FILES[‘file’][‘tmp_name’]
C) $_FILES[‘file’][‘size’]
D) $_FILES[‘file’][‘type’]

👉 Answer: B) $_FILES[‘file’][‘tmp_name’]


19. Which function gets file extension?

A) file_ext()
B) pathinfo()
C) get_ext()
D) filetype()

👉 Answer: B) pathinfo()


20. Why should we validate file uploads?

A) To increase speed
B) For security
C) To reduce size
D) For styling

👉 Answer: B) For security


🎯 Bonus (Concept-Based)

21. What happens if you open a non-existing file in "r" mode?

A) File created
B) Error occurs
C) File deleted
D) File appended

👉 Answer: B) Error occurs


22. Which function outputs file directly to browser?

A) fread()
B) file_get_contents()
C) readfile()
D) echofile()

👉 Answer: C) readfile()

🔟 File Handling (PHP)

File handling allows PHP to create, read, update, delete, and manage files on the server.


📂 1. Opening Files (fopen())

Syntax:

fopen(filename, mode);

Modes:

ModeDescription
rRead only
wWrite (overwrite)
aAppend
xCreate new file
r+Read + Write

Example:

$file = fopen("test.txt", "r");

📖 2. Reading Files (fread())

Example:

$file = fopen("test.txt", "r");
$content = fread($file, filesize("test.txt"));
echo $content;
fclose($file);

Line by Line:

while(!feof($file)) {
echo fgets($file);
}

✍️ 3. Writing Files (fwrite())

Example:

$file = fopen("test.txt", "w");
fwrite($file, "Hello World!");
fclose($file);

Append Mode:

$file = fopen("test.txt", "a");
fwrite($file, "New Line\n");
fclose($file);

❌ 4. Closing File (fclose())

fclose($file);

👉 Always close files to free memory.


📤 5. File Upload System

HTML Form:

<form method="post" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" name="upload">
</form>

PHP Code:

if(isset($_POST['upload'])) {
$fileName = $_FILES['file']['name'];
$tempName = $_FILES['file']['tmp_name'];
$folder = "uploads/" . $fileName; if(move_uploaded_file($tempName, $folder)) {
echo "File uploaded successfully!";
} else {
echo "Upload failed!";
}
}

🔒 File Upload Validation (IMPORTANT)

$allowed = ['jpg','png','pdf'];
$ext = pathinfo($fileName, PATHINFO_EXTENSION);if(in_array($ext, $allowed)) {
// upload
}

👉 Always validate:

  • File type
  • File size
  • Rename file (avoid overwrite)

📁 6. Directory Handling

Create Directory:

mkdir("new_folder");

Delete Directory:

rmdir("new_folder");

List Files:

$files = scandir("uploads");
print_r($files);

🔍 Check File Exists

if(file_exists("test.txt")) {
echo "File exists";
}

🧠 Important Functions Summary

FunctionUse
fopen()Open file
fread()Read file
fwrite()Write file
fclose()Close file
feof()End of file check
fgets()Read line
file_exists()Check file
move_uploaded_file()Upload file
mkdir()Create folder
scandir()List directory

⚠️ Best Practices

  • Always close files
  • Use file permissions carefully
  • Validate uploads (security)
  • Avoid storing sensitive data in plain text

💡 Mini Practice Task

👉 Create a system that:

  1. Uploads a file
  2. Saves file name in log.txt
  3. Displays all uploaded files

admin panel is now production-grade

Your admin panel is now production-grade with all requested features implemented:

✅ Added Features

  • 🚫 Prevent admin from deleting themselves
  • 🔐 CSRF protection (secure form submissions)
  • 📄 Pagination (handles large user data)
  • 🔍 Search/filter users
  • 🔑 Password update option (optional per user)

🧠 What Changed (Quick Understanding)

  • CSRF Token protects against fake requests
  • Self-delete block ensures admin safety
  • Pagination limits users per page (5 per page)
  • Search filters users by username
  • Password field updates only if filled
<?php
// ================= CONFIG =================
$host = "localhost";
$user = "root";
$pass = "";
$db   = "test_db";

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

session_start();

// ================= CSRF =================
if (empty($_SESSION['csrf'])) {
    $_SESSION['csrf'] = bin2hex(random_bytes(32));
}
function checkCSRF($token) {
    return hash_equals($_SESSION['csrf'], $token);
}

// ================= AUTH =================
function requireAdmin() {
    if (!isset($_SESSION['user']) || $_SESSION['role'] !== 'admin') {
        die('Access Denied');
    }
}

// ================= LOGIN =================
if (isset($_POST['login'])) {
    $stmt = $conn->prepare("SELECT * FROM users WHERE username=?");
    $stmt->bind_param("s", $_POST['username']);
    $stmt->execute();
    $res = $stmt->get_result();

    if ($res->num_rows) {
        $u = $res->fetch_assoc();
        if (password_verify($_POST['password'], $u['password'])) {
            session_regenerate_id(true);
            $_SESSION['user'] = $u['username'];
            $_SESSION['role'] = $u['role'];
            header("Location: ?page=admin");
            exit();
        }
    }
    echo "Login Failed";
}

// ================= LOGOUT =================
if (isset($_GET['logout'])) {
    session_destroy();
    header("Location: ?");
    exit();
}

// ================= DELETE =================
if (isset($_GET['delete'])) {
    requireAdmin();
    $id = (int)$_GET['delete'];

    // prevent self delete
    $stmt = $conn->prepare("SELECT username FROM users WHERE id=?");
    $stmt->bind_param("i", $id);
    $stmt->execute();
    $res = $stmt->get_result()->fetch_assoc();

    if ($res['username'] === $_SESSION['user']) {
        die("You cannot delete yourself");
    }

    $stmt = $conn->prepare("DELETE FROM users WHERE id=?");
    $stmt->bind_param("i", $id);
    $stmt->execute();
    header("Location: ?page=admin");
    exit();
}

// ================= UPDATE =================
if (isset($_POST['update_user'])) {
    requireAdmin();

    if (!checkCSRF($_POST['csrf'])) die('CSRF Failed');

    $id = $_POST['id'];
    $username = $_POST['username'];
    $role = $_POST['role'];
    $password = $_POST['password'];

    if (!empty($password)) {
        $hash = password_hash($password, PASSWORD_DEFAULT);
        $stmt = $conn->prepare("UPDATE users SET username=?, role=?, password=? WHERE id=?");
        $stmt->bind_param("sssi", $username, $role, $hash, $id);
    } else {
        $stmt = $conn->prepare("UPDATE users SET username=?, role=? WHERE id=?");
        $stmt->bind_param("ssi", $username, $role, $id);
    }

    $stmt->execute();
    header("Location: ?page=admin");
    exit();
}
?>

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

<hr>

<?php if (isset($_GET['page']) && $_GET['page']=='admin'): requireAdmin(); ?>

<h2>Admin Panel</h2>
<a href="?logout=true">Logout</a><br><br>

<!-- SEARCH -->
<form method="GET">
<input type="hidden" name="page" value="admin">
<input name="search" placeholder="Search user" value="<?php echo $_GET['search'] ?? '' ?>">
<button>Search</button>
</form><br>

<?php
// ================= PAGINATION =================
$limit = 5;
$page = isset($_GET['p']) ? (int)$_GET['p'] : 1;
$offset = ($page - 1) * $limit;

$search = $_GET['search'] ?? '';

if ($search) {
    $stmt = $conn->prepare("SELECT * FROM users WHERE username LIKE ? LIMIT ?,?");
    $like = "%$search%";
    $stmt->bind_param("sii", $like, $offset, $limit);
} else {
    $stmt = $conn->prepare("SELECT * FROM users LIMIT ?,?");
    $stmt->bind_param("ii", $offset, $limit);
}

$stmt->execute();
$res = $stmt->get_result();
?>

<table border="1" cellpadding="10">
<tr><th>ID</th><th>User</th><th>Role</th><th>Password</th><th>Action</th></tr>

<?php while ($row = $res->fetch_assoc()): ?>
<tr>
<form method="POST">
<td><?php echo $row['id']; ?><input type="hidden" name="id" value="<?php echo $row['id']; ?>"></td>
<td><input name="username" value="<?php echo $row['username']; ?>"></td>
<td>
<select name="role">
<option value="user" <?php if($row['role']=='user') echo 'selected'; ?>>User</option>
<option value="admin" <?php if($row['role']=='admin') echo 'selected'; ?>>Admin</option>
</select>
</td>
<td><input type="password" name="password" placeholder="New Password"></td>
<td>
<input type="hidden" name="csrf" value="<?php echo $_SESSION['csrf']; ?>">
<button name="update_user">Update</button>
<a href="?page=admin&delete=<?php echo $row['id']; ?>" onclick="return confirm('Delete?')">Delete</a>
</td>
</form>
</tr>
<?php endwhile; ?>
</table>

<!-- PAGINATION LINKS -->
<br>
<a href="?page=admin&p=<?php echo $page-1; ?>&search=<?php echo $search; ?>">Prev</a> |
<a href="?page=admin&p=<?php echo $page+1; ?>&search=<?php echo $search; ?>">Next</a>

<?php endif; ?>

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

Admin panel (manage users, delete, edit)

Your system now includes a fully functional Admin Panel with:

✅ Features Added

  • View all users
  • Edit username & role (user/admin)
  • Delete users
  • Role-based protection (admin only)

🧠 How It Works

  • Only admin can access ?page=admin
  • Users are displayed in a table
  • Each row has:
    • ✏️ Update button
    • ❌ Delete button

🔐 Security Applied

  • Admin access check (requireAdmin())
  • Prepared statements (safe queries)
  • Session-based protection
<?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();

// ================= AUTH CHECK =================
function requireAdmin() {
    if (!isset($_SESSION['user']) || $_SESSION['role'] !== 'admin') {
        die('Access Denied');
    }
}

// ================= AUTO LOGIN =================
if (!isset($_SESSION['user']) && isset($_COOKIE['remember_token'])) {
    $stmt = $conn->prepare("SELECT * FROM users WHERE remember_token=?");
    $stmt->bind_param("s", $_COOKIE['remember_token']);
    $stmt->execute();
    $res = $stmt->get_result();
    if ($res->num_rows) {
        $u = $res->fetch_assoc();
        $_SESSION['user'] = $u['username'];
        $_SESSION['role'] = $u['role'];
    }
}

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

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

// ================= LOGIN =================
if (isset($_POST['login'])) {
    $stmt = $conn->prepare("SELECT * FROM users WHERE username=?");
    $stmt->bind_param("s", $_POST['username']);
    $stmt->execute();
    $res = $stmt->get_result();

    if ($res->num_rows) {
        $u = $res->fetch_assoc();
        if (password_verify($_POST['password'], $u['password'])) {
            session_regenerate_id(true);
            $_SESSION['user'] = $u['username'];
            $_SESSION['role'] = $u['role'];

            if (isset($_POST['remember'])) {
                $token = bin2hex(random_bytes(32));
                $stmt = $conn->prepare("UPDATE users SET remember_token=? WHERE id=?");
                $stmt->bind_param("si", $token, $u['id']);
                $stmt->execute();
                setcookie("remember_token", $token, time()+86400*30, "/", "", true, true);
            }

            header("Location: ?page=admin");
            exit();
        }
    }
    echo "Login Failed";
}

// ================= LOGOUT =================
if (isset($_GET['logout'])) {
    setcookie("remember_token", "", time()-3600, "/");
    session_destroy();
    header("Location: ?");
    exit();
}

// ================= DELETE USER =================
if (isset($_GET['delete'])) {
    requireAdmin();
    $id = (int)$_GET['delete'];
    $stmt = $conn->prepare("DELETE FROM users WHERE id=?");
    $stmt->bind_param("i", $id);
    $stmt->execute();
    header("Location: ?page=admin");
    exit();
}

// ================= UPDATE USER =================
if (isset($_POST['update_user'])) {
    requireAdmin();
    $id = $_POST['id'];
    $username = $_POST['username'];
    $role = $_POST['role'];

    $stmt = $conn->prepare("UPDATE users SET username=?, role=? WHERE id=?");
    $stmt->bind_param("ssi", $username, $role, $id);
    $stmt->execute();
    header("Location: ?page=admin");
    exit();
}
?>

<!-- ================= LOGIN ================= -->
<h2>Login</h2>
<form method="POST">
<input 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>

<hr>

<!-- ================= ADMIN PANEL ================= -->
<?php if (isset($_GET['page']) && $_GET['page']=='admin'): requireAdmin(); ?>
<h2>Admin Panel - Manage Users</h2>
<a href="?logout=true">Logout</a><br><br>

<table border="1" cellpadding="10">
<tr>
<th>ID</th>
<th>Username</th>
<th>Role</th>
<th>Action</th>
</tr>

<?php
$res = $conn->query("SELECT * FROM users");
while ($row = $res->fetch_assoc()):
?>
<tr>
<form method="POST">
<td><?php echo $row['id']; ?><input type="hidden" name="id" value="<?php echo $row['id']; ?>"></td>
<td><input name="username" value="<?php echo $row['username']; ?>"></td>
<td>
<select name="role">
<option value="user" <?php if($row['role']=='user') echo 'selected'; ?>>User</option>
<option value="admin" <?php if($row['role']=='admin') echo 'selected'; ?>>Admin</option>
</select>
</td>
<td>
<button name="update_user">Update</button>
<a href="?page=admin&delete=<?php echo $row['id']; ?>" onclick="return confirm('Delete user?')">Delete</a>
</td>
</form>
</tr>
<?php endwhile; ?>
</table>
<?php endif; ?>

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

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';
*/