✅ Build a complete REST API project (CRUD + JWT login)

I’ve built a complete working PHP REST API project with JWT login + CRUD for you in the canvas.

🚀 What this project includes:

  • ✅ User Registration (/register)
  • ✅ User Login with JWT (/login)
  • ✅ Protected Routes (Middleware)
  • ✅ Product CRUD:
    • GET /products
    • POST /products
    • DELETE /products/{id}
  • ✅ Database structure (MySQL)
  • ✅ Simple routing system
  • ✅ Authentication middleware

⚠️ Important (Real-World Upgrade)

This project is educational. For production:

  • Replace custom JWT with: composer require firebase/php-jwt
  • Add:
    • Token expiry
    • Signature verification
    • Input validation
    • Rate limiting
    • HTTPS

🧪 How to Test (Postman)

1. Register

POST /register
{
"name": "Aditya",
"email": "test@test.com",
"password": "123456"
}

2. Login

POST /login

➡️ Copy token

3. Access Protected API

GET /products
Authorization: Bearer YOUR_TOKEN
<?php
// ===============================
// SIMPLE PHP REST API WITH JWT
// ===============================

header("Content-Type: application/json");

// -------------------------------
// DATABASE CONNECTION
// -------------------------------
class Database {
    private $host = "localhost";
    private $db_name = "api_db";
    private $username = "root";
    private $password = "";
    public $conn;

    public function connect() {
        $this->conn = null;
        try {
            $this->conn = new PDO(
                "mysql:host=" . $this->host . ";dbname=" . $this->db_name,
                $this->username,
                $this->password
            );
            $this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        } catch(PDOException $e) {
            echo json_encode(["error" => $e->getMessage()]);
        }
        return $this->conn;
    }
}

// -------------------------------
// SIMPLE JWT FUNCTIONS
// -------------------------------
class JWT {
    private static $secret = "MY_SECRET_KEY";

    public static function encode($payload) {
        return base64_encode(json_encode($payload));
    }

    public static function decode($token) {
        return json_decode(base64_decode($token), true);
    }
}

// -------------------------------
// USER MODEL
// -------------------------------
class User {
    private $conn;
    private $table = "users";

    public function __construct($db) {
        $this->conn = $db;
    }

    public function register($name, $email, $password) {
        $query = "INSERT INTO users (name, email, password) VALUES (?, ?, ?)";
        $stmt = $this->conn->prepare($query);
        $hashed = password_hash($password, PASSWORD_DEFAULT);
        return $stmt->execute([$name, $email, $hashed]);
    }

    public function login($email, $password) {
        $query = "SELECT * FROM users WHERE email = ?";
        $stmt = $this->conn->prepare($query);
        $stmt->execute([$email]);
        $user = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($user && password_verify($password, $user['password'])) {
            return JWT::encode(["user_id" => $user['id']]);
        }
        return false;
    }
}

// -------------------------------
// PRODUCT MODEL (CRUD)
// -------------------------------
class Product {
    private $conn;
    private $table = "products";

    public function __construct($db) {
        $this->conn = $db;
    }

    public function getAll() {
        $stmt = $this->conn->query("SELECT * FROM products");
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }

    public function create($name) {
        $stmt = $this->conn->prepare("INSERT INTO products (name) VALUES (?)");
        return $stmt->execute([$name]);
    }

    public function delete($id) {
        $stmt = $this->conn->prepare("DELETE FROM products WHERE id = ?");
        return $stmt->execute([$id]);
    }
}

// -------------------------------
// AUTH MIDDLEWARE
// -------------------------------
function authenticate() {
    $headers = getallheaders();

    if (!isset($headers['Authorization'])) {
        http_response_code(401);
        echo json_encode(["message" => "Unauthorized"]);
        exit;
    }

    $token = str_replace("Bearer ", "", $headers['Authorization']);
    return JWT::decode($token);
}

// -------------------------------
// ROUTER
// -------------------------------
$db = (new Database())->connect();
$user = new User($db);
$product = new Product($db);

$request = $_SERVER['REQUEST_URI'];
$method = $_SERVER['REQUEST_METHOD'];
$data = json_decode(file_get_contents("php://input"), true);

// -------------------------------
// ROUTES
// -------------------------------

// REGISTER
if ($request == '/register' && $method == 'POST') {
    $user->register($data['name'], $data['email'], $data['password']);
    echo json_encode(["message" => "User Registered"]);
}

// LOGIN
elseif ($request == '/login' && $method == 'POST') {
    $token = $user->login($data['email'], $data['password']);
    if ($token) {
        echo json_encode(["token" => $token]);
    } else {
        echo json_encode(["message" => "Invalid credentials"]);
    }
}

// GET PRODUCTS (Protected)
elseif ($request == '/products' && $method == 'GET') {
    authenticate();
    echo json_encode($product->getAll());
}

// CREATE PRODUCT (Protected)
elseif ($request == '/products' && $method == 'POST') {
    authenticate();
    $product->create($data['name']);
    echo json_encode(["message" => "Product Created"]);
}

// DELETE PRODUCT
elseif (preg_match('/\/products\/(\d+)/', $request, $matches) && $method == 'DELETE') {
    authenticate();
    $product->delete($matches[1]);
    echo json_encode(["message" => "Deleted"]);
}

else {
    echo json_encode(["message" => "Route Not Found"]);
}

// ===============================
// DATABASE SQL
// ===============================
/*
CREATE DATABASE api_db;

CREATE TABLE users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(100),
    email VARCHAR(100),
    password TEXT
);

CREATE TABLE products (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(100)
);
*/

🛠️ 19. Advanced Topics (PHP)

1️⃣ RESTful API Development

🔹 What is REST API?

REST (Representational State Transfer) is a way to build APIs using HTTP methods.

🔹 HTTP Methods:

  • GET → Fetch data
  • POST → Create data
  • PUT/PATCH → Update data
  • DELETE → Remove data

🔹 Example (Simple PHP API)

<?php
header("Content-Type: application/json");$data = [
["id" => 1, "name" => "Aditya"],
["id" => 2, "name" => "Rahul"]
];echo json_encode($data);

🔹 API Routing (Basic)

$request = $_SERVER['REQUEST_METHOD'];if ($request == 'GET') {
echo "Fetching data";
} elseif ($request == 'POST') {
echo "Creating data";
}

🔹 Best Practices:

  • Use JSON format
  • Proper HTTP status codes (200, 404, 500)
  • Secure endpoints
  • Version your API (/api/v1/)

2️⃣ Authentication (JWT & Sessions)

🔹 Session Authentication

  • Stores user data on server
  • Uses cookies
session_start();$_SESSION['user'] = "Aditya";if(isset($_SESSION['user'])){
echo "Logged in as " . $_SESSION['user'];
}

🔹 JWT (JSON Web Token)

Stateless authentication (no session stored on server)

🔹 JWT Flow:

  1. User logs in
  2. Server generates token
  3. Client stores token
  4. Token sent in headers for every request

🔹 Example (Concept)

$token = base64_encode(json_encode(["user_id" => 1]));
echo $token;

🔹 Real JWT uses:

  • Signature
  • Secret key
  • Expiry time

Libraries:

  • firebase/php-jwt

3️⃣ Middleware

🔹 What is Middleware?

Middleware acts as a filter before request reaches main logic.

🔹 Use Cases:

  • Authentication check
  • Logging
  • Rate limiting

🔹 Example

function authMiddleware() {
if(!isset($_SESSION['user'])) {
die("Unauthorized");
}
}

Usage:

authMiddleware();
echo "Protected Content";

4️⃣ Dependency Injection (DI)

🔹 What is DI?

Instead of creating objects inside a class, you pass them from outside.

❌ Without DI

class User {
public function __construct() {
$this->db = new Database();
}
}

✅ With DI

class User {
private $db; public function __construct($db) {
$this->db = $db;
}
}$db = new Database();
$user = new User($db);

🔹 Benefits:

  • Easy testing
  • Loose coupling
  • Better code structure

🚀 Pro Tips (Important for Students & Developers)

  • Use MVC framework (Laravel) for real projects
  • Always validate & sanitize input
  • Secure APIs with JWT + HTTPS
  • Use Postman for API testing
  • Follow PSR standards

Prepare company-level interview set (TCS, Infosys, Startup)

🚀 1. TCS Interview Set (Service-Based – Moderate Level)

🧠 Round 1: Aptitude + Basics

  • What is OOP?
  • Difference between == and === in PHP
  • Output-based questions (loops, arrays)
  • SQL: JOIN, GROUP BY, COUNT

💻 Round 2: Technical

PHP / Laravel

  1. What is MVC?
  2. How Laravel routing works?
  3. Difference between echo and print?
  4. What is session & cookie?
  5. Write a simple CRUD logic.

Coding Question

👉 Reverse a string without using built-in function

$str = "TCS";

👉 Find largest number in array

$arr = [10, 45, 2, 89, 32];

👨‍💼 Round 3: HR

  • Tell me about yourself
  • Why TCS?
  • Are you ready for relocation?
  • Strengths & weaknesses

🏢 2. Infosys Interview Set (Structured + Conceptual)

🧠 Round 1: Written Test

  • OOP concepts
  • DBMS basics
  • Output prediction
  • Basic coding

💻 Round 2: Technical Deep

Core Questions

  1. Explain OOP with example
  2. What is normalization?
  3. Difference between GET and POST
  4. What is framework?

Laravel Focus

  1. What is middleware?
  2. What is migration?
  3. Explain authentication

Coding Questions

👉 Palindrome check

madam

👉 Count vowels in string

👉 Fibonacci series


👨‍💼 HR Round

  • Why Infosys?
  • Describe a challenge you solved
  • Teamwork experience
  • Career goals

⚡ 3. Startup Interview Set (High-Level 🔥)

💻 Round 1: Practical Coding

Real Tasks

👉 Build simple API (CRUD)

GET /users
POST /users
PUT /users/{id}
DELETE /users/{id}

👉 Create login system

  • Email + password
  • Validation
  • Session handling

🧠 Round 2: Deep Technical

Laravel / Backend

  1. Explain request lifecycle
  2. How to optimize performance?
  3. What is caching?
  4. How authentication works internally?
  5. REST API best practices

Database

  1. Indexing?
  2. N+1 problem?
  3. Query optimization?

🔥 System Design (Basic)

  • Design a blog system
  • Design login system
  • How to scale API?

👨‍💼 Final Round (Founder/Manager)

  • Show your projects
  • Explain real problems you solved
  • How fast can you learn?
  • Salary expectation

💣 Startup Coding Test (IMPORTANT)

👉 Build this in interview:

  1. CRUD App (Laravel)
  2. Login + Auth
  3. API with JSON
  4. Database design

🎯 Preparation Strategy

For TCS / Infosys

  • Focus on basics + theory
  • Practice small coding
  • Clear concepts

For Startups 🔥

  • Focus on real projects
  • Strong Laravel knowledge
  • API + Authentication
  • Database optimization

💡 Pro Tip (Very Important)

👉 Service companies test knowledge
👉 Startups test skills + real work

clear, interview-ready answers (short + powerful)

🔥 Laravel Interview Answers

🟢 Basic

1. What is Laravel?
Laravel is an open-source PHP framework based on MVC architecture, used to build secure, scalable, and maintainable web applications بسرعة with clean syntax.

2. What is MVC?
MVC = Model (data), View (UI), Controller (logic). It separates concerns for clean code.

3. What is routing?
Routing maps URLs to controllers or functions. Example:

Route::get('/home', [HomeController::class, 'index']);

4. Blade template?
Laravel’s templating engine to write dynamic HTML using simple syntax like {{ }}.

5. Middleware?
Filters HTTP requests (e.g., authentication check before accessing route).

6. Eloquent ORM?
Laravel’s ORM to interact with DB using models instead of raw SQL.

7. GET vs POST?
GET = fetch data (visible in URL)
POST = send data securely (not in URL)


🟡 Intermediate

1. Migration?
Version control for database (create/update tables using PHP).

2. Seeder?
Used to insert dummy/test data into database.

3. CSRF?
Security token to prevent unauthorized form submission.

4. Authentication?
Laravel provides built-in auth (login/register) via Breeze, Jetstream.

5. Service Container?
Manages class dependencies automatically.

6. Dependency Injection?
Automatically injects required classes into controller.

7. Facade?
Static interface to Laravel services (e.g., DB::table()).

8. hasOne vs hasMany?
hasOne = one-to-one
hasMany = one-to-many


🔴 Advanced

1. Request lifecycle?
Request → Middleware → Route → Controller → Response

2. Queue & Job?
Used for background tasks (emails, notifications).

3. Event & Listener?
Event triggers action, listener handles it.

4. Caching?
Stores frequently used data to improve speed.

5. API Resource?
Formats API responses in structured JSON.

6. Performance optimization?

  • Cache routes/config
  • Use queues
  • Optimize queries
  • Use CDN

7. Repository pattern?
Separates business logic from controller.

8. Security best practices?

  • Use validation
  • CSRF protection
  • Hash passwords
  • Avoid raw SQL

⚡ CodeIgniter Answers

🟢 Basic

1. CodeIgniter?
Lightweight PHP framework for fast development.

2. MVC?
Same structure (Model, View, Controller).

3. Controller?
Handles user request and loads views/models.

4. DB connection?
Configured in application/config/database.php.

5. Helper?
Predefined functions (URL, form, etc.)


🟡 Intermediate

1. Session?
Stores user data across requests.

2. Form validation?
Validates input using built-in library.

3. Routing?
Maps URL to controller.

4. Active Record?
Query builder for database operations.


🔴 Advanced

1. Performance improvement?

  • Enable caching
  • Optimize queries
  • Compress output

2. CI3 vs CI4?
CI4 is modern, faster, PSR compliant.

3. REST API?
Using controllers + JSON response.

4. Security?

  • XSS filtering
  • CSRF protection
  • Input validation

🧠 Symfony Answers

🟢 Basic

1. Symfony?
A powerful PHP framework for enterprise apps.

2. Bundles?
Reusable packages (like modules).

3. Routing?
Maps URLs to controllers.


🟡 Intermediate

1. Dependency Injection?
Inject services automatically.

2. Service Container?
Manages services and dependencies.

3. Doctrine ORM?
Database abstraction tool.


🔴 Advanced

1. Architecture?
Highly modular, component-based.

2. Reusable components?
Independent packages used in other frameworks.

3. Large apps?
Scalable, structured code, service-based.

4. Laravel vs Symfony?
Laravel = easy, fast
Symfony = complex, enterprise-level


💥 HR + Practical Answers

Explain project
Explain: Problem → Your role → Tech → Result
Example:
“I built a Laravel blog with auth, CRUD, and REST API.”

Error handling?
Use try-catch, logs, Laravel exception handler.

Security?
Validation, CSRF, hashing, authentication.

REST API?
Use routes + controllers + JSON response.

Deployment?

  • Upload to server
  • Setup DB
  • Run migrations
  • Configure .env

🎯 Final Tip

In interview:
👉 Speak simple
👉 Give real examples
👉 Show project experience

🚀 PHP Framework Interview Questions


🔥 Laravel Interview Questions

🟢 Basic

  1. What is Laravel?
  2. What is MVC architecture?
  3. What is routing in Laravel?
  4. What is Blade template?
  5. What is middleware?
  6. What is Eloquent ORM?
  7. Difference between GET and POST routes?

🟡 Intermediate

  1. What is migration in Laravel?
  2. What are seeders?
  3. What is CSRF protection?
  4. Explain authentication in Laravel.
  5. What is a service container?
  6. What is dependency injection?
  7. What is a facade in Laravel?
  8. Difference between hasOne and hasMany?

🔴 Advanced

  1. Explain Laravel request lifecycle.
  2. What is queue and job in Laravel?
  3. What is event & listener?
  4. How caching works in Laravel?
  5. What is API resource?
  6. How to optimize Laravel performance?
  7. What is repository pattern?
  8. Explain Laravel security best practices.

⚡ CodeIgniter Interview Questions

🟢 Basic

  1. What is CodeIgniter?
  2. What is MVC in CodeIgniter?
  3. What are controllers?
  4. How to connect database?
  5. What is helper?

🟡 Intermediate

  1. What is session handling?
  2. What is form validation?
  3. What is routing in CodeIgniter?
  4. What is Active Record?

🔴 Advanced

  1. How to improve performance?
  2. Difference between CodeIgniter 3 vs 4?
  3. How to build REST API in CodeIgniter?
  4. Security features in CodeIgniter?

🧠 Symfony Interview Questions

🟢 Basic

  1. What is Symfony?
  2. What are bundles?
  3. What is routing?

🟡 Intermediate

  1. What is dependency injection in Symfony?
  2. What is service container?
  3. What is Doctrine ORM?

🔴 Advanced

  1. Explain Symfony architecture.
  2. What are reusable components?
  3. How Symfony handles large applications?
  4. Difference between Laravel and Symfony?

💥 HR + Practical Questions

  • Explain your last project (Laravel/CI)
  • How do you handle errors?
  • How do you secure a PHP application?
  • How to design REST API?
  • What is your deployment process?

🎯 Pro Tips (Important for Selection)

  • Always explain with real project example
  • Know CRUD + Auth + API
  • Be ready to write basic code
  • Focus more on Laravel 🔥

🚀 18. PHP Frameworks (Overview + Practice)

🔹 Why Frameworks?

  • Faster development
  • Better security
  • Clean code (MVC structure)
  • Reusable components
  • Industry standard

🔥 1. Laravel (Most Important)

📌 Overview

  • Most popular PHP framework
  • Based on MVC architecture
  • Clean syntax + powerful features

⭐ Key Features

  • Routing system
  • Blade templating engine
  • Eloquent ORM (database handling)
  • Authentication system
  • Middleware
  • REST API support

🛠 Practice Projects

1️⃣ Blog System (CRUD)
2️⃣ User Login & Registration
3️⃣ REST API (CRUD)
4️⃣ Admin Dashboard
5️⃣ E-commerce (Advanced)

📚 What to Teach

  • Installation (Composer)
  • Routes (web.php)
  • Controllers
  • Views (Blade)
  • Models & Migration
  • Forms & Validation
  • Authentication (Laravel Breeze)

⚡ 2. CodeIgniter

📌 Overview

  • Lightweight & fast framework
  • Easy for beginners
  • Less strict structure

⭐ Key Features

  • Simple MVC
  • Fast performance
  • Minimal configuration
  • Small size

🛠 Practice Projects

1️⃣ Simple CRUD App
2️⃣ Contact Form
3️⃣ Login System
4️⃣ Blog System (basic)

📚 What to Teach

  • Installation
  • Routing
  • Controllers & Views
  • Database connection
  • CRUD operations

🧠 3. Symfony (Advanced)

📌 Overview

  • Enterprise-level framework
  • Used in large applications
  • Complex but powerful

⭐ Key Features

  • Reusable components
  • Highly scalable
  • Professional architecture
  • Used by big companies

🛠 Practice Projects

1️⃣ REST API
2️⃣ Large-scale backend system
3️⃣ Microservices architecture

📚 What to Teach

  • Basic setup
  • Routing
  • Controllers
  • Services & Dependency Injection
  • API development

🎯 Recommended Learning Order

👉 Start with:

  1. Laravel (Main focus 🔥)
  2. CodeIgniter (for basics clarity)
  3. Symfony (only for advanced students)

💡 Pro Teaching Tip

  • Spend 70% time on Laravel
  • Build real-world projects
  • Focus on CRUD + Authentication + API

real-world MVC with MySQL + PDO + full CRUD system

Your project is now upgraded to a real-world MVC with MySQL + PDO + full CRUD system.

🚀 What you now have

  • PDO database connection (secure)
  • Full CRUD:
    • /User → List users
    • /User/add → Add user
    • /User/edit/1 → Edit user
    • /User/delete/1 → Delete user
  • Clean routing with parameters
  • Reusable database class

⚠️ Important setup steps

  1. Create database:
CREATE DATABASE mvc_app;
  1. Create table (already in code, just run it)
  2. Update DB credentials in:
/config/config.php
  1. Run project:
http://localhost/User
<?php
// ======================================
// FULL MVC WITH DATABASE + CRUD (PDO)
// ======================================

/*
UPDATED STRUCTURE
/project
│
├── /app
│   ├── /controllers
│   │     └── UserController.php
│   │
│   ├── /models
│   │     └── UserModel.php
│   │
│   └── /views
│         ├── users.php
│         ├── add.php
│         └── edit.php
│
├── /core
│   ├── Router.php
│   ├── Controller.php
│   └── Database.php
│
├── /config
│   └── config.php
│
├── /public
│   └── index.php
│
└── .htaccess
*/

// ======================================
// DATABASE: config/config.php
// ======================================

return [
    'host' => 'localhost',
    'dbname' => 'mvc_app',
    'user' => 'root',
    'pass' => ''
];


// ======================================
// core/Database.php (PDO)
// ======================================

class Database {
    private static $instance = null;

    public static function connect() {
        if (self::$instance === null) {
            $config = require '../config/config.php';

            try {
                self::$instance = new PDO(
                    "mysql:host={$config['host']};dbname={$config['dbname']}",
                    $config['user'],
                    $config['pass']
                );
                self::$instance->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            } catch (PDOException $e) {
                die("DB Error: " . $e->getMessage());
            }
        }
        return self::$instance;
    }
}


// ======================================
// core/Router.php
// ======================================

class Router {
    public function dispatch($url) {
        $url = trim($url, '/');
        $parts = explode('/', $url);

        $controllerName = !empty($parts[0]) ? ucfirst($parts[0]) . 'Controller' : 'UserController';
        $method = $parts[1] ?? 'index';
        $param = $parts[2] ?? null;

        require_once "../app/controllers/$controllerName.php";

        $controller = new $controllerName();

        if (!method_exists($controller, $method)) {
            die('Method not found');
        }

        $controller->$method($param);
    }
}


// ======================================
// core/Controller.php
// ======================================

class Controller {
    public function view($view, $data = []) {
        extract($data);
        require "../app/views/$view.php";
    }
}


// ======================================
// public/index.php
// ======================================

require_once '../core/Router.php';

$url = $_GET['url'] ?? '';
$router = new Router();
$router->dispatch($url);


// ======================================
// app/models/UserModel.php
// ======================================

require_once '../core/Database.php';

class UserModel {
    private $db;

    public function __construct() {
        $this->db = Database::connect();
    }

    public function getAll() {
        return $this->db->query("SELECT * FROM users")->fetchAll(PDO::FETCH_ASSOC);
    }

    public function getById($id) {
        $stmt = $this->db->prepare("SELECT * FROM users WHERE id=?");
        $stmt->execute([$id]);
        return $stmt->fetch(PDO::FETCH_ASSOC);
    }

    public function create($name) {
        $stmt = $this->db->prepare("INSERT INTO users (name) VALUES (?)");
        return $stmt->execute([$name]);
    }

    public function update($id, $name) {
        $stmt = $this->db->prepare("UPDATE users SET name=? WHERE id=?");
        return $stmt->execute([$name, $id]);
    }

    public function delete($id) {
        $stmt = $this->db->prepare("DELETE FROM users WHERE id=?");
        return $stmt->execute([$id]);
    }
}


// ======================================
// app/controllers/UserController.php
// ======================================

require_once '../core/Controller.php';
require_once '../app/models/UserModel.php';

class UserController extends Controller {

    public function index() {
        $model = new UserModel();
        $users = $model->getAll();
        $this->view('users', compact('users'));
    }

    public function add() {
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $model = new UserModel();
            $model->create($_POST['name']);
            header('Location: /User');
        }
        $this->view('add');
    }

    public function edit($id) {
        $model = new UserModel();

        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $model->update($id, $_POST['name']);
            header('Location: /User');
        }

        $user = $model->getById($id);
        $this->view('edit', compact('user'));
    }

    public function delete($id) {
        $model = new UserModel();
        $model->delete($id);
        header('Location: /User');
    }
}


// ======================================
// app/views/users.php
// ======================================
?>
<h2>User List</h2>
<a href="/User/add">Add User</a>
<ul>
<?php foreach($users as $u): ?>
    <li>
        <?= $u['name'] ?>
        <a href="/User/edit/<?= $u['id'] ?>">Edit</a>
        <a href="/User/delete/<?= $u['id'] ?>">Delete</a>
    </li>
<?php endforeach; ?>
</ul>

<?php
// ======================================
// app/views/add.php
// ======================================
?>
<h2>Add User</h2>
<form method="POST">
    <input type="text" name="name" required>
    <button>Add</button>
</form>

<?php
// ======================================
// app/views/edit.php
// ======================================
?>
<h2>Edit User</h2>
<form method="POST">
    <input type="text" name="name" value="<?= $user['name'] ?>">
    <button>Update</button>
</form>

<?php
// ======================================
// SQL TABLE
// ======================================
/*
CREATE TABLE users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(100) NOT NULL
);
*/

Php Mvc Project With Routing (complete Example)

I’ve created a complete working MVC project with routing for you in the canvas.

This is not just theory — you can copy this and run it directly.

🚀 How to run it

  1. Create the folder structure exactly as shown
  2. Put files in correct folders
  3. Enable Apache mod_rewrite
  4. Open in browser:
    • http://localhost/ → Home page
    • http://localhost/Home/users → Users page

🔥 What this project includes

  • Clean MVC structure
  • Custom Router (no framework)
  • Dynamic URL handling
  • Controller → Model → View flow
  • Reusable base controller
<?php
// ===============================
// PROJECT STRUCTURE
// ===============================
/*
/project
│
├── /app
│   ├── /controllers
│   │     └── HomeController.php
│   │
│   ├── /models
│   │     └── UserModel.php
│   │
│   └── /views
│         ├── home.php
│         └── users.php
│
├── /core
│   ├── Router.php
│   └── Controller.php
│
├── /public
│   └── index.php
│
└── .htaccess
*/

// ===============================
// .htaccess (URL Routing)
// ===============================
/*
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.+)$ public/index.php?url=$1 [QSA,L]
*/

// ===============================
// public/index.php (Entry Point)
// ===============================

require_once '../core/Router.php';

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

$router = new Router();
$router->dispatch($url);


// ===============================
// core/Router.php
// ===============================

class Router {
    public function dispatch($url) {
        $url = trim($url, '/');
        $parts = explode('/', $url);

        $controllerName = !empty($parts[0]) ? ucfirst($parts[0]) . 'Controller' : 'HomeController';
        $method = $parts[1] ?? 'index';

        $controllerFile = "../app/controllers/$controllerName.php";

        if (!file_exists($controllerFile)) {
            die('Controller not found');
        }

        require_once $controllerFile;

        $controller = new $controllerName();

        if (!method_exists($controller, $method)) {
            die('Method not found');
        }

        $controller->$method();
    }
}


// ===============================
// core/Controller.php (Base Controller)
// ===============================

class Controller {
    public function view($view, $data = []) {
        extract($data);
        require "../app/views/$view.php";
    }
}


// ===============================
// app/controllers/HomeController.php
// ===============================

require_once '../core/Controller.php';
require_once '../app/models/UserModel.php';

class HomeController extends Controller {

    public function index() {
        $this->view('home', ['title' => 'Welcome MVC']);
    }

    public function users() {
        $model = new UserModel();
        $users = $model->getUsers();

        $this->view('users', ['users' => $users]);
    }
}


// ===============================
// app/models/UserModel.php
// ===============================

class UserModel {
    public function getUsers() {
        return [
            ['name' => 'Aditya'],
            ['name' => 'Rahul'],
            ['name' => 'Priya']
        ];
    }
}


// ===============================
// app/views/home.php
// ===============================
?>
<!DOCTYPE html>
<html>
<head>
    <title><?= $title ?></title>
</head>
<body>
    <h1><?= $title ?></h1>
    <a href="/Home/users">View Users</a>
</body>
</html>

<?php
// ===============================
// app/views/users.php
// ===============================
?>
<!DOCTYPE html>
<html>
<head>
    <title>Users</title>
</head>
<body>
    <h2>User List</h2>
    <ul>
        <?php foreach($users as $user): ?>
            <li><?= $user['name'] ?></li>
        <?php endforeach; ?>
    </ul>

    <a href="/">Back Home</a>
</body>
</html>

🧩 17. MVC Architecture (PHP)

🔹 What is MVC?

MVC = Model + View + Controller

It is a design pattern used to organize code into 3 parts:

1️⃣ Model (Data Layer)

  • Handles database & business logic
  • Fetches, inserts, updates data
  • Example:
class UserModel {
public function getUsers() {
// fetch data from database
}
}

2️⃣ View (UI Layer)

  • Responsible for frontend / UI
  • Displays data to user
  • Example:
<h1>Welcome <?= $name ?></h1>

3️⃣ Controller (Logic Layer)

  • Connects Model + View
  • Handles user request
  • Example:
class UserController {
public function index() {
$model = new UserModel();
$data = $model->getUsers();
include 'views/users.php';
}
}

🔄 How MVC Works (Flow)

  1. User opens URL → /users
  2. Request goes to Controller
  3. Controller calls Model
  4. Model fetches data from DB
  5. Controller sends data to View
  6. View shows result to user

👉 Simple Flow:

User → Controller → Model → Controller → View → User

📁 Folder Structure (Basic MVC in PHP)

/project

├── /app
│ ├── /controllers
│ │ └── UserController.php
│ │
│ ├── /models
│ │ └── UserModel.php
│ │
│ └── /views
│ └── users.php

├── /core
│ └── Router.php

├── /config
│ └── database.php

├── /public
│ └── index.php (Entry point)

└── .htaccess

🛠️ Basic MVC Project (Simple Example)

📍 1. public/index.php (Entry Point)

require_once '../app/controllers/UserController.php';$controller = new UserController();
$controller->index();

📍 2. Controller (UserController.php)

require_once '../app/models/UserModel.php';class UserController {
public function index() {
$model = new UserModel();
$users = $model->getUsers(); require '../app/views/users.php';
}
}

📍 3. Model (UserModel.php)

class UserModel {
public function getUsers() {
return [
['name' => 'Aditya'],
['name' => 'Rahul']
];
}
}

📍 4. View (users.php)

<h2>User List</h2><ul>
<?php foreach($users as $user): ?>
<li><?= $user['name'] ?></li>
<?php endforeach; ?>
</ul>

🔥 Why Use MVC?

✔ Clean code
✔ Easy to maintain
✔ Scalable projects
✔ Team-friendly (frontend + backend separation)


⚡ Pro Tips (Real-World Use)

  • Use Router for clean URLs (/users, /products)
  • Add Database connection class
  • Use autoloading (PSR-4) instead of manual require
  • Use frameworks like:
    • Laravel (Best for MVC in PHP)
    • CodeIgniter (Lightweight)

🚀 Simple Summary

PartWork
ModelData + Database
ViewUI / Design
ControllerLogic + Flow Control

complete Login System + Database integration

🟢 Step 1: Database Setup

👉 Create Database

CREATE DATABASE composer_exam;

👉 Create Users Table

USE composer_exam;CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100),
email VARCHAR(100) UNIQUE,
password VARCHAR(255),
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

🟢 Step 2: Install DB Package (Optional but Professional)

You can use raw PDO (recommended for learning), no extra package needed.


🟢 Step 3: Create DB Connection

📁 config/db.php

<?php$host = "localhost";
$dbname = "composer_exam";
$username = "root";
$password = "";try {
$pdo = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
die("DB Connection Failed: " . $e->getMessage());
}

🟡 Step 4: Register System

📁 register.php

<?php
require 'vendor/autoload.php';
require 'config/db.php';if ($_SERVER['REQUEST_METHOD'] == 'POST') { $name = $_POST['name'];
$email = $_POST['email'];
$password = password_hash($_POST['password'], PASSWORD_BCRYPT); if (!$name || !$email || !$password) {
die("All fields required!");
} $stmt = $pdo->prepare("INSERT INTO users (name, email, password) VALUES (?, ?, ?)"); try {
$stmt->execute([$name, $email, $password]);
echo "User registered successfully!";
} catch (Exception $e) {
echo "Email already exists!";
}
}

📁 register.html

<form method="POST" action="register.php">
Name: <input type="text" name="name" required><br><br>
Email: <input type="email" name="email" required><br><br>
Password: <input type="password" name="password" required><br><br>
<button type="submit">Register</button>
</form>

🟡 Step 5: Login System

📁 login.php

<?php
session_start();require 'vendor/autoload.php';
require 'config/db.php';if ($_SERVER['REQUEST_METHOD'] == 'POST') { $email = $_POST['email'];
$password = $_POST['password']; $stmt = $pdo->prepare("SELECT * FROM users WHERE email = ?");
$stmt->execute([$email]); $user = $stmt->fetch(PDO::FETCH_ASSOC); if ($user && password_verify($password, $user['password'])) { $_SESSION['user'] = $user['name'];
header("Location: dashboard.php"); } else {
echo "Invalid credentials!";
}
}

📁 login.html

<form method="POST" action="login.php">
Email: <input type="email" name="email" required><br><br>
Password: <input type="password" name="password" required><br><br>
<button type="submit">Login</button>
</form>

🔴 Step 6: Dashboard (Protected Page)

📁 dashboard.php

<?php
session_start();if (!isset($_SESSION['user'])) {
header("Location: login.html");
exit;
}echo "Welcome, " . $_SESSION['user'];
echo "<br><a href='logout.php'>Logout</a>";

🔴 Step 7: Logout

📁 logout.php

<?php
session_start();
session_destroy();header("Location: login.html");

🟠 Step 8: Logging Login Activity (Using Monolog)

👉 Add this inside login.php after successful login:

use Monolog\Logger;
use Monolog\Handler\StreamHandler;$log = new Logger('auth');
$log->pushHandler(new StreamHandler('logs/app.log', Logger::INFO));$log->info("User logged in: " . $email);

🟠 Step 9: Folder Structure (Final)

composer-exam/

├── config/
│ └── db.php
├── src/
├── logs/
├── vendor/

├── register.php
├── register.html
├── login.php
├── login.html
├── dashboard.php
├── logout.php

🔐 Security Best Practices (Important)

  • ✅ Use password_hash() (already done)
  • ✅ Use password_verify()
  • ✅ Use prepared statements (PDO ✔)
  • ✅ Never store plain passwords
  • ✅ Add input validation (can improve)

🚀 Bonus Upgrades (Industry Level)

If you want to go pro level, add:

  • 🔹 CSRF protection
  • 🔹 Email verification
  • 🔹 Forgot password system
  • 🔹 .env (hide DB credentials)
  • 🔹 MVC structure