PART 5 of 5  •  about 20 class hours

Professional PHP & Projects

A complete CRUD app, authentication and security, Composer and REST APIs, then capstone projects, deployment and your career.

17

Building a CRUD Web App

10 examples  •  5 h
18

Authentication & Security

10 examples  •  5 h
19

Composer, REST APIs & Testing

10 examples  •  5 h
20

Capstone Projects, Deployment & Career

10 examples  •  5 h
🐘
<?php
PHP 8.3  •  MySQL  •  XAMPP
BrainBit Infotech, Ranchi  |  Complete PHP 8.3 Course  |  Keys: ← → navigate   M menu   L Code Lab   F fullscreen
M17

Building a CRUD Web App

Everything so far comes together: a complete Student Management System with list, add, edit, delete, search, pagination, validation, flash messages, CSV export and a mini MVC structure.

  • Planning pages, tables and flow
  • Project structure and a bootstrap file
  • List, Create, Edit, Delete (CRUD)
  • Shared validation and form partials
  • Search, pagination and CSV export
  • The MVC idea: models, views, controllers
YOU WILL BUILD:
Student Management SystemCSV exportMini MVC framework
💻
Part 5  •  about 5 hours
10 practice examples: 5 Easy • 3 Medium • 2 Hard
Complete PHP 8.3 Course  |  BrainBit Infotech, Ranchi
M17Where is this used in real work?

CRUD is 80% of business software

localhost:8000/index.php
BrainBit Infotech SMS   Students | + Add
Student Kunal Sahu added (id 9)
#NameCityCourse
9Kunal SahuHazaribaghPython BasicsEdit | Delete
8Deepak MahtoBokaroPHP & MySQLEdit | Delete
📝

Create, Read, Update, Delete

Students, products, patients, vehicles, invoices: every admin panel is CRUD screens on database tables.
💼

Freelance projects

Most small-business projects in Ranchi and Patna are CRUD apps: a school ERP, a clinic register, a shop inventory.
🧱

Laravel does the same

Frameworks generate exactly these screens. Building them by hand first makes frameworks easy to understand.
Complete PHP 8.3 Course  |  Part 5  |  Building a CRUD Web App
M17Planning

Plan before you code

📄

Pages

index.php list + search
create.php add form
edit.php?id= edit form
delete.php?id= confirm
export.php CSV
🗃

Tables

courses(id, name)
students(id, name, mobile UNIQUE, city, course_id FK, created_at)
🔁

Flow

Form POST → validate → save → flash message → redirect to list (PRG)
📁 student-sms/
  bootstrap.php session, db(), e(), flash(), redirect()
  header.php, footer.php layout
  validate.php, _form.php shared by add + edit
  index.php, create.php, edit.php, delete.php, export.php
How the examples workExamples 1-8 build this app step by step; every run resets the database to the same 8 students. Example 9 reorganises it as mini-MVC and Example 10 is the complete system.
Complete PHP 8.3 Course  |  Part 5  |  Building a CRUD Web App
M17Animated explainer

The CRUD cycle

C

Create

form → INSERT
create.php
R

Read

SELECT → table
index.php
U

Update

load row → form → UPDATE
edit.php?id=3
D

Delete

confirm → POST → DELETE
delete.php?id=3
POST form➤validate➤SQL (prepared)➤flash("Saved")➤302 → index.php➤list shows message
Deleting with a GET link is dangerousBrowsers and bots pre-load links. A link should only show a confirmation page; the actual delete happens on POST.
Complete PHP 8.3 Course  |  Part 5  |  Building a CRUD Web App
M17Animated explainer

MVC: Model, View, Controller

💻
Browser
➤
ControllerStudentController::index()
decides what to do
⇄
ModelStudent::all(), find(), save()
talks to MySQL
➤
Viewviews/students/index.php
only HTML + <?= ?>
WhyEach file has one job. Designers edit views, database changes stay in models, and controllers stay short. Laravel, CodeIgniter and Symfony all follow MVC.
Complete PHP 8.3 Course  |  Part 5  |  Building a CRUD Web App
M17Practice 1 of 10  •  Easy

Example 1: bootstrap.php: the shared start file

● Easy💼 Real project: The first file of every PHP project
One file that every page requires: session, database connection (created once), escaping helper, flash messages and redirect. never is the return type of a function that always exits.
test.phpbootstrap.php
REAL RUN
✍ Try it yourself Add a helper old(string $field) that returns the escaped POST value or an empty string.
function old(string $f): string { return e($_POST[$f] ?? ''); }
Complete PHP 8.3 Course  |  Part 5  |  Building a CRUD Web App
M17Practice 2 of 10  •  Easy

Example 2: List students page

● Easy💼 Real project: The "index" screen of admin panels
A JOIN brings the course name, the layout comes from header/footer, and every value is escaped with e().
index.phpbootstrap.phpheader.phpfooter.php
REAL RUN
✍ Try it yourself Show the date each student was added (created_at) in d-m-Y format.
Select s.created_at and print date('d-m-Y', strtotime($r['created_at'])).
Complete PHP 8.3 Course  |  Part 5  |  Building a CRUD Web App
M17Practice 3 of 10  •  Easy

Example 3: Add student form

● Easy💼 Real project: Admission and registration screens
GET shows an empty form; POST validates, INSERTs, sets a flash message and redirects to the list (PRG). Validation and the form are shared files, used again by Edit.
create.phpvalidate.php_form.phpindex.phpbootstrap.phpheader.phpfooter.php
REAL RUN
✍ Try it yourself Add an optional email field (validate with filter_var only if it is not empty).
Add the column with ALTER TABLE, a field in _form.php and a rule in validateStudent().
Complete PHP 8.3 Course  |  Part 5  |  Building a CRUD Web App
M17Practice 4 of 10  •  Easy

Example 4: Edit student

● Easy💼 Real project: Updating records
The same form, pre-filled from the database. The uniqueness check ignores the student's own row (id <> ?). Unknown ids return 404.
edit.phpvalidate.php_form.phpindex.phpbootstrap.phpheader.phpfooter.php
REAL RUN
✍ Try it yourself Add a "last updated" column that is set with NOW() on every update.
ALTER TABLE students ADD updated_at DATETIME NULL; and add updated_at = NOW() to the UPDATE.
Complete PHP 8.3 Course  |  Part 5  |  Building a CRUD Web App
M17Practice 5 of 10  •  Easy

Example 5: Delete with confirmation

● Easy💼 Real project: Safe deletion in admin panels
The Delete link only shows a confirmation page. The row is deleted only when the form is POSTed. After deleting, the flash message appears on the list.
delete.phpindex.phpbootstrap.phpheader.phpfooter.php
REAL RUN
✍ Try it yourself Make it a "soft delete": set deleted_at instead of deleting, and hide those rows in the list.
ALTER TABLE ADD deleted_at DATETIME NULL; UPDATE ... SET deleted_at = NOW(); list with WHERE deleted_at IS NULL.
Complete PHP 8.3 Course  |  Part 5  |  Building a CRUD Web App
M17Practice 6 of 10  •  Medium

Example 6: Search + pagination

● Medium💼 Real project: Lists with hundreds of records
One query with LIKE for search, LIMIT and OFFSET for pages, and a COUNT(*) with the same filter for the page count. Links keep the search text.
index.phpbootstrap.phpheader.phpfooter.php
REAL RUN
✍ Try it yourself Add a course filter (select box) that works together with the search box.
Add AND (:cid = 0 OR s.course_id = :cid) to $where and keep cid in the links.
Complete PHP 8.3 Course  |  Part 5  |  Building a CRUD Web App
M17Practice 7 of 10  •  Medium

Example 7: Validation + flash messages (the full add flow)

● Medium💼 Real project: Every data-entry screen
Walk through the full flow with the Database tab open: invalid data is rejected with messages, valid data is saved, the redirect shows the flash once, and a refresh shows the list without it.
create.phpvalidate.php_form.phpindex.phpbootstrap.phpheader.phpfooter.php
REAL RUN
✍ Try it yourself Show the number of students per course above the table.
SELECT c.name, COUNT(s.id) FROM courses c LEFT JOIN students s ... GROUP BY c.id.
Complete PHP 8.3 Course  |  Part 5  |  Building a CRUD Web App
M17Practice 8 of 10  •  Medium

Example 8: Export to CSV

● Medium💼 Real project: "Download Excel" buttons in reports
Stream rows from MySQL straight into the download with fputcsv on php://output. The BOM line makes Excel read Hindi and other Unicode text correctly.
export.phpbootstrap.phpheader.phpfooter.php
REAL RUN
✍ Try it yourself Export only the students of one course: export.php?course=2.
Add WHERE s.course_id = ? with a prepared statement when the parameter is present.
Complete PHP 8.3 Course  |  Part 5  |  Building a CRUD Web App
M17Practice 9 of 10  •  Hard

Example 9: Mini MVC structure

● Hard💼 Real project: Understanding Laravel and CodeIgniter
The same app as tiny MVC: index.php is the front controller, StudentController handles actions, the Student model holds all SQL, and views contain only HTML.
index.phpapp/Student.phpapp/StudentController.phpviews/students/index.phpviews/students/show.phpbootstrap.php
REAL RUN
✍ Try it yourself Add a route courses with a CourseController and a view.
Create app/Course.php (model), app/CourseController.php and views/courses/index.php; add one match arm.
Complete PHP 8.3 Course  |  Part 5  |  Building a CRUD Web App
M17Practice 10 of 10  •  Hard

Example 10: Complete Student Management System

● Hard💼 Real project: A deliverable project for a coaching centre client
All the pieces in one app: list with search, add, edit, delete with confirmation, flash messages and CSV export. Follow the full journey in the Browser tab and the final table in the Database tab.
index.phpcreate.phpedit.phpdelete.phpvalidate.php_form.phpbootstrap.phpheader.phpfooter.php
REAL RUN
✍ Try it yourself Add a dashboard page with total students, students per course and the 3 newest admissions.
Use COUNT(*), GROUP BY course_id and ORDER BY created_at DESC LIMIT 3 queries on dashboard.php.
Complete PHP 8.3 Course  |  Part 5  |  Building a CRUD Web App
M17Check your understanding

Quick Quiz

Click an answer. Wrong answers shake; the right one turns green and explains why.

Q1. Which request should actually delete a record?
✔ GET links can be pre-fetched by browsers or bots.
Q2. In MVC, where does SQL belong?
✔ Controllers call models; views only display.
Q3. Why share _form.php between create and edit?
✔ Change a field once; both screens update.
🎯
Your score: 0 / 3 (first try counts)
Answer all questions. Discuss any wrong answer with your partner before moving on.
Complete PHP 8.3 Course  |  Part 5  |  Building a CRUD Web App
M17Module summary

Recap: Building a CRUD Web App

What you learned in M17

  • ✔Plan pages, tables and flow before coding.
  • ✔bootstrap.php centralises session, db(), e(), flash(), redirect().
  • ✔CRUD: create.php (INSERT), index.php (SELECT), edit.php (UPDATE), delete.php (confirm + POST DELETE).
  • ✔Shared validation and form partials keep add and edit identical.
  • ✔Search with LIKE, paginate with LIMIT/OFFSET, export with fputcsv to php://output.
  • ✔MVC: controllers coordinate, models hold SQL, views hold HTML.
🏆

Module 17 complete!

You practised 10 real examples.

👉 Coming next

M18 Authentication & Security: real user accounts with hashed passwords, roles, CSRF tokens and login limits.
Complete PHP 8.3 Course  |  Part 5  |  Building a CRUD Web App
M18

Authentication & Security

Every real app has users. You will build registration and login the right way: hashed passwords, safe sessions, roles, CSRF protection, login limits and password reset, plus a checklist of the top web attacks.

  • password_hash and password_verify
  • Registration and login flow
  • Protecting pages and roles
  • XSS, SQL injection and CSRF
  • Session fixation, secure cookies, login rate limits
  • Password reset with expiring tokens
YOU WILL BUILD:
Register / login / logoutRole-based admin pageLogin attempt limiterForgot password
🔐
Part 5  •  about 5 hours
10 practice examples: 5 Easy • 3 Medium • 2 Hard
Complete PHP 8.3 Course  |  BrainBit Infotech, Ranchi
M18Where is this used in real work?

Login systems protect real people

portal.school.in/login.php
🔒 Staff LoginPHP
tirkey@brainbit-teaching.com
••••••••
Too many attempts. Try again in 10 minutes.
users.password_hash:
$2y$12$Qm8k...Zt1e
(never the real password)
🔑

Passwords

Stored only as slow, salted hashes. Even the developer cannot read them; a leaked database does not leak passwords.
👥

Roles

Admin, teacher, student and parent each see different pages. Every private page checks the role on the server.
🛡️

Attacks are daily

Bots try common passwords, SQL injection and fake forms on every public site, including small school portals.
Complete PHP 8.3 Course  |  Part 5  |  Authentication & Security
M18Animated explainer

Why we hash passwords (and add salt)

❌ Plain text

riya@gmail.com | Riya@2026
A database leak exposes every password, and people reuse passwords for email and UPI.

A hash is one-way

password → hash function → fixed scrambled text. You cannot turn it back.

Salt

A random value added before hashing. Two users with the same password get different hashes, so pre-computed lists are useless.
password_hash('Riya@2026', PASSWORD_DEFAULT)
→ $2y$12$8Hq1nX...salt...kTz...hash...

$2y$ = bcrypt, 12 = cost (slowness), then salt + hash
password_verify('Riya@2026', $hash) → true
password_verify('riya@2026', $hash) → false
Neveruse md5() or sha1() for passwords; they are far too fast to brute force. password_hash is slow on purpose and handles the salt for you. Use VARCHAR(255) for the column.
Complete PHP 8.3 Course  |  Part 5  |  Authentication & Security
M18Concept

password_hash and password_verify

  • Registration: $hash = password_hash($pw, PASSWORD_DEFAULT); store $hash.
  • Login: password_verify($typed, $hashFromDb) returns true/false.
  • Same password twice gives different hashes (different salts): both verify.
  • password_needs_rehash() lets you upgrade old hashes when PHP improves the default.
Output differs on every runHashes include a random salt, so your output will not match these characters. That is correct.
hash.php
REAL RUN
Complete PHP 8.3 Course  |  Part 5  |  Authentication & Security
M18Animated explainer

CSRF: a fake form on another site

1. Teacher is logged in

school-erp.in session cookie is in her browser.

2. She opens a prize link

evil.example has a hidden auto-submitting form:
<form action="https://school-erp.in/delete.php" method="post"><input name="id" value="ALL">

3. The browser sends her cookie

The ERP sees a valid session and would delete the data!

✅ Fix: a secret token in every form

<input type="hidden" name="csrf" value="<?= csrfToken() ?>">
The token is random and stored in her session. evil.example cannot read it.

On POST: compare

hash_equals($_SESSION['csrf'], $_POST['csrf'])
Missing or wrong token → reject (419).
Also helpsSameSite=Lax cookies are not sent with cross-site POSTs in modern browsers. Use both.
Complete PHP 8.3 Course  |  Part 5  |  Authentication & Security
M18Checklist

Security checklist for every PHP project

ThreatDefence in PHP
SQL injectionPrepared statements for every value
XSShtmlspecialchars on every output
CSRFToken in forms + SameSite cookies
Weak password storagepassword_hash / password_verify
Session hijack / fixationHTTPS, httponly cookies, session_regenerate_id
Brute forceLimit attempts per account and IP
Broken access controlCheck role on the server on every page
Malicious uploadsSize, real MIME, random names, no PHP in uploads
Secrets in code.env / config outside the web root
Error leaksdisplay_errors=Off in production + logs

🔗 OWASP Top 10

The OWASP Top 10 lists the most critical web application risks. Read it once; every item on the left maps to it.

🔒 Always HTTPS

Free certificates from Let's Encrypt (cPanel: AutoSSL). Never send passwords over plain http.

🔄 Keep PHP updated

PHP 8.3 gets security fixes until 31 Dec 2027; plan upgrades to 8.4/8.5 before then.
Complete PHP 8.3 Course  |  Part 5  |  Authentication & Security
M18Practice 1 of 10  •  Easy

Example 1: Hash and verify

● Easy💼 Real project: Changing how a legacy app stores passwords
An old app stored plain passwords. This one-time script converts them to hashes; afterwards login uses password_verify. The Database tab shows the result.
migrate.php
REAL RUN
✍ Try it yourself Add password_needs_rehash to a login function so hashes are upgraded automatically.
After a successful verify: if (password_needs_rehash($hash, PASSWORD_DEFAULT)) { update with a new password_hash($typed, ...) }
Complete PHP 8.3 Course  |  Part 5  |  Authentication & Security
M18Practice 2 of 10  •  Easy

Example 2: Register a user

● Easy💼 Real project: Sign-up pages
Validate, check the email is not taken, hash the password, INSERT with the default role "student", then log the user in. The Database tab shows only a hash.
register.phpauth.php
REAL RUN
✍ Try it yourself Add a "confirm password" field.
Compare $_POST['password'] with $_POST['confirm'] and add an error if different.
Complete PHP 8.3 Course  |  Part 5  |  Authentication & Security
M18Practice 3 of 10  •  Easy

Example 3: Login

● Easy💼 Real project: Every member area
Look up the user by email, verify the hash, regenerate the session id, store minimal user info. Wrong email and wrong password give the same message so attackers cannot discover which emails exist.
login.phpdashboard.phpauth.php
REAL RUN
✍ Try it yourself Log in as tirkey@brainbit-teaching.com with Staff@2026. What role is shown?
staff. Roles come from the users table.
Complete PHP 8.3 Course  |  Part 5  |  Authentication & Security
M18Practice 4 of 10  •  Easy

Example 4: Protected dashboard

● Easy💼 Real project: Member-only pages
requireRole() at the top of a page sends guests to the login page. One line protects any page.
dashboard.phplogin.phpauth.php
REAL RUN
✍ Try it yourself Protect a new page reports.php for staff and admin only.
$u = requireRole('staff', 'admin'); at the top.
Complete PHP 8.3 Course  |  Part 5  |  Authentication & Security
M18Practice 5 of 10  •  Easy

Example 5: Logout

● Easy💼 Real project: Ending sessions properly
Logout empties the session, expires the session cookie and destroys the server data. Going back to the dashboard afterwards redirects to login.
logout.phplogin.phpdashboard.phpauth.php
REAL RUN
✍ Try it yourself Show "You have been logged out" on the login page after logout.
Redirect to login.php?bye=1 and show a message when $_GET['bye'] is set.
Complete PHP 8.3 Course  |  Part 5  |  Authentication & Security
M18Practice 6 of 10  •  Medium

Example 6: Role-based admin page

● Medium💼 Real project: Admin / staff / student permissions
The admin page calls requireRole('admin'). A student gets 403 Forbidden even if she types the URL directly: hiding the menu link is not security; the server check is.
admin.phplogin.phpdashboard.phplogout.phpauth.php
REAL RUN
✍ Try it yourself Make a teacher-only page marks.php that admins can also open.
requireRole('staff', 'admin')
Complete PHP 8.3 Course  |  Part 5  |  Authentication & Security
M18Practice 7 of 10  •  Medium

Example 7: CSRF token on a form

● Medium💼 Real project: Every form that changes data
The form includes a hidden token from the session; the handler checks it with hash_equals. A forged POST without the token gets status 419.
profile.phplogin.phpdashboard.phpauth.php
REAL RUN
✍ Try it yourself Look at the Request tab of step 2. Where is the token?
In the HTML as a hidden input. The attacker's site cannot read pages from your domain, so it cannot copy the token.
Complete PHP 8.3 Course  |  Part 5  |  Authentication & Security
M18Practice 8 of 10  •  Medium

Example 8: Login attempt limiter

● Medium💼 Real project: Stopping password-guessing bots
Each failed login is recorded. After 3 failures for an email in 10 minutes, further attempts are blocked, even with the right password, until the window passes.
login.phpauth.php
REAL RUN
✍ Try it yourself Also limit by IP address: at most 10 failures per IP in 10 minutes.
Run a second COUNT(*) query WHERE ip = ? and block when it reaches 10.
Complete PHP 8.3 Course  |  Part 5  |  Authentication & Security
M18Practice 9 of 10  •  Hard

Example 9: Forgot password with a token

● Hard💼 Real project: Password reset emails
A random token is created, only its hash is stored with a 30-minute expiry, and the reset link would be emailed (here it is shown on screen for the demo). The token works once, then is deleted.
forgot.phpreset.phpshow-link.phpauth.php
REAL RUN
✍ Try it yourself Why store hash('sha256', $token) instead of the token itself?
If the database leaks, stored hashes cannot be used as reset links. Only the email has the real token.
Complete PHP 8.3 Course  |  Part 5  |  Authentication & Security
M18Practice 10 of 10  •  Hard

Example 10: Full auth system (MySQL)

● Hard💼 Real project: The login module of a school or business portal
All parts together: login, dashboard, role-protected admin page, CSRF-protected profile form and logout, on the same users table. Follow the journey of a staff user.
login.phpdashboard.phplogout.phpauth.phpadmin.phpstudents.php
REAL RUN
✍ Try it yourself Add an audit log table that records every login and logout with time and IP.
INSERT INTO audit (user_id, action, ip) in login() and in logout.php.
Complete PHP 8.3 Course  |  Part 5  |  Authentication & Security
M18Check your understanding

Quick Quiz

Click an answer. Wrong answers shake; the right one turns green and explains why.

Q1. How should passwords be stored?
✔ Slow, salted, one-way.
Q2. What does a CSRF token protect against?
✔ The other site cannot know the secret token.
Q3. A student types /admin.php. What protects the page?
✔ Only server-side checks are real security.
🎯
Your score: 0 / 3 (first try counts)
Answer all questions. Discuss any wrong answer with your partner before moving on.
Complete PHP 8.3 Course  |  Part 5  |  Authentication & Security
M18Module summary

Recap: Authentication & Security

What you learned in M18

  • ✔password_hash to store, password_verify to check; never md5/sha1 or plain text.
  • ✔Login: find by email, verify, session_regenerate_id, store minimal user info.
  • ✔requireRole() on every private page; 403 for the wrong role.
  • ✔CSRF tokens in forms + SameSite cookies; hash_equals to compare secrets.
  • ✔Limit failed logins; same error message for wrong email or password.
  • ✔Reset links use random tokens stored as hashes with an expiry, used once.
🏆

Module 18 complete!

You practised 10 real examples.

👉 Coming next

M19 Composer, REST APIs & Testing: autoloading, JSON APIs for mobile apps, and testing your code.
Complete PHP 8.3 Course  |  Part 5  |  Authentication & Security
M19

Composer, REST APIs & Testing

Professional PHP: Composer for autoloading and packages, REST APIs that serve JSON to mobile apps and JavaScript front-ends, and automated tests that prove your code works.

  • Composer, composer.json and PSR-4 autoloading
  • Packages from Packagist (overview)
  • REST: resources, methods, status codes, JSON
  • A front-controller API with routing
  • Validation errors, API keys, pagination
  • Testing: assertions, a tiny test runner and PHPUnit
YOU WILL BUILD:
Courses REST APIProducts API with MySQLTest suite for a GST calculator
🚀
Part 5  •  about 5 hours
10 practice examples: 5 Easy • 3 Medium • 2 Hard
Complete PHP 8.3 Course  |  BrainBit Infotech, Ranchi
M19Where is this used in real work?

APIs connect PHP to apps everywhere

Android app
📱
BrainBit Infotech Student App

Courses • Fees • Attendance

GET /api/courses/1
200 OK
{"id":1,"name":"PHP & MySQL",
 "fee":12000,"months":4}

The same PHP API serves the website, the Android app, and partner systems.

📱

Mobile apps

Flutter and Android apps do not use PHP pages; they call JSON APIs. Your PHP code becomes their back end.
📦

Composer everywhere

Laravel, PHPMailer, payment SDKs (Razorpay), PDF and Excel libraries: all installed with Composer.
✅

Tests save money

A test suite catches a broken GST calculation before customers see a wrong invoice.
Complete PHP 8.3 Course  |  Part 5  |  Composer, REST APIs & Testing
M19Concept

Composer and PSR-4 autoloading

  • Composer is PHP's package manager. Install from getcomposer.org (Windows installer finds XAMPP's php.exe).
  • composer.json describes your project; the autoload section maps a namespace to a folder.
  • composer dump-autoload writes vendor/autoload.php. One require loads every class.
  • Packages: composer require phpmailer/phpmailer downloads into vendor/ (needs internet; the build machine had none, so only autoloading is run here).
  • Commit composer.json and composer.lock, never vendor/.
index.phpcomposer.jsonsrc/Gst.phpsrc/Invoice.php
REAL RUN
Complete PHP 8.3 Course  |  Part 5  |  Composer, REST APIs & Testing
M19Animated explainer

REST: resources, methods and status codes

Method + URLMeaningSuccessTypical errors
GET /api/courseslist all200
GET /api/courses/2one course200404 not found
POST /api/coursescreate (JSON body)201 Created400 bad JSON, 422 invalid data
PUT /api/courses/2replace / update200404, 422
DELETE /api/courses/2delete204 No Content404

Nouns in URLs

/api/courses/2, not /getCourse.php?id=2

JSON in, JSON out

Content-Type: application/json both ways

Stateless

Each request carries its own auth (API key / token)
Complete PHP 8.3 Course  |  Part 5  |  Composer, REST APIs & Testing
M19Concept

Reading JSON requests and sending responses

  • Form posts fill $_POST; JSON bodies do not. Read them with file_get_contents('php://input').
  • Check with json_validate() (PHP 8.3), then json_decode($raw, true).
  • Answer with a status code and json_encode. A small respond() helper keeps every endpoint consistent.
Request tabShows each API call like Postman or Thunder Client (VS Code extension): method, JSON body, status, headers, response.
echo.php
REAL RUN
Complete PHP 8.3 Course  |  Part 5  |  Composer, REST APIs & Testing
M19Concept

Testing your code

  • A test runs your function with known inputs and checks the output automatically.
  • Write tests for rules that must never break: GST, fees, discounts, validation.
  • Re-run all tests after every change: if something breaks, you know immediately.
  • PHPUnit is the standard tool (composer require --dev phpunit/phpunit). Its asserts look like the ones in this tiny runner.
Red, green, refactorWrite a failing test (red), make it pass (green), then clean up the code with the tests protecting you.
test.php
REAL RUN
Complete PHP 8.3 Course  |  Part 5  |  Composer, REST APIs & Testing
M19Practice 1 of 10  •  Easy

Example 1: Composer autoload for a project

● Easy💼 Real project: Starting every modern PHP project
A composer.json with PSR-4 autoloading; composer dump-autoload generates the loader. Adding a class is now just: create the file in src/ with the right namespace.
app.phpcomposer.jsonsrc/Attendance/Status.phpsrc/Attendance/Register.php
REAL RUN
✍ Try it yourself Look at vendor/composer/autoload_psr4.php in the Files tab. What does it map?
'School\\' => [$baseDir . '/src']: the namespace prefix to the folder.
Complete PHP 8.3 Course  |  Part 5  |  Composer, REST APIs & Testing
M19Practice 2 of 10  •  Easy

Example 2: GET /api/courses

● Easy💼 Real project: Course list for a mobile app
A front controller (php -S localhost:8000 index.php) receives every URL. It splits the path into parts and answers the collection with JSON.
index.phpcourses.json
REAL RUN
✍ Try it yourself Add ?max_fee=10000 to filter courses by fee.
array_filter($courses, fn($c) => $c['fee'] <= (int) $_GET['max_fee']) before respond().
Complete PHP 8.3 Course  |  Part 5  |  Composer, REST APIs & Testing
M19Practice 3 of 10  •  Easy

Example 3: GET /api/courses/{id} with 404

● Easy💼 Real project: Detail screens in apps
The id comes from the URL path. A missing course returns status 404 with a JSON error, so the app can show "not found" properly.
index.phpcourses.json
REAL RUN
✍ Try it yourself Return 400 if the id is not a positive number (e.g. /api/courses/abc).
Check ctype_digit($parts[2]) before converting.
Complete PHP 8.3 Course  |  Part 5  |  Composer, REST APIs & Testing
M19Practice 4 of 10  •  Easy

Example 4: POST create with 201

● Easy💼 Real project: Adding records from an app
The app sends JSON; the API validates the JSON (with PHP 8.3's json_validate inside body()), saves it and answers 201 Created with a Location header for the new resource.
index.phpcourses.json
REAL RUN
✍ Try it yourself Reject a new course whose name already exists with status 409 Conflict.
if (in_array(strtolower($new['name']), array_map('strtolower', array_column($courses, 'name')))) respond([...], 409);
Complete PHP 8.3 Course  |  Part 5  |  Composer, REST APIs & Testing
M19Practice 5 of 10  •  Easy

Example 5: PUT and DELETE

● Easy💼 Real project: Edit and remove from an app
PUT updates only the allowed fields (array_intersect_key ignores anything else, like a fake "id"). DELETE answers 204 with an empty body. The Files tab shows courses.json after the calls.
index.phpcourses.json
REAL RUN
✍ Try it yourself Add PATCH as a synonym for PUT.
'PUT', 'PATCH' => ... in the match.
Complete PHP 8.3 Course  |  Part 5  |  Composer, REST APIs & Testing
M19Practice 6 of 10  •  Medium

Example 6: Validation errors 422

● Medium💼 Real project: Signup and order APIs
Invalid data gets 422 Unprocessable Content with an errors object per field: the app can highlight each field. This is the same format Laravel uses.
index.php
REAL RUN
✍ Try it yourself Add a rule: age must be between 14 and 60.
if (!is_int($in['age'] ?? null) || $in['age'] < 14 || $in['age'] > 60) $errors['age'][] = '...';
Complete PHP 8.3 Course  |  Part 5  |  Composer, REST APIs & Testing
M19Practice 7 of 10  •  Medium

Example 7: API key authentication

● Medium💼 Real project: Partner and app access to private data
Private endpoints need a key in the X-API-Key header. Keys are compared with hash_equals. Missing key: 401; wrong key: 403.
index.php
REAL RUN
✍ Try it yourself Log every request with the client name and time to api.log.
file_put_contents('api.log', date('c') . " $client {$_SERVER['REQUEST_URI']}\n", FILE_APPEND);
Complete PHP 8.3 Course  |  Part 5  |  Composer, REST APIs & Testing
M19Practice 8 of 10  •  Medium

Example 8: Pagination + search API

● Medium💼 Real project: Infinite scroll lists in apps
Query parameters control the result: ?q= search, ?page= and ?per_page= (capped at 50). The response includes meta so the app knows how many pages exist.
index.php
REAL RUN
✍ Try it yourself Add ?sort=price and ?sort=-price (descending), allowing only known columns.
Map ['price' => 'price ASC', '-price' => 'price DESC'] and put the mapped value into ORDER BY (never the raw input).
Complete PHP 8.3 Course  |  Part 5  |  Composer, REST APIs & Testing
M19Practice 9 of 10  •  Hard

Example 9: Products REST API with MySQL

● Hard💼 Real project: Back end of an e-commerce app
A complete small API: list, show, create (validated), update stock, delete, with a tiny router that matches method + path pattern with regex. Every query is prepared. The Database tab shows the table after all calls.
index.php
REAL RUN
✍ Try it yourself Add GET /api/products/low-stock that lists products with stock below 10.
Add a route ['GET', '#^/api/products/low-stock$#', ...] BEFORE the (\d+) route, with WHERE stock < 10.
Complete PHP 8.3 Course  |  Part 5  |  Composer, REST APIs & Testing
M19Practice 10 of 10  •  Hard

Example 10: Tiny test runner for a GST calculator

● Hard💼 Real project: Testing billing rules before release
A minimal test framework in 30 lines: test functions, assertions, exception tests and a summary with an exit code (CI servers fail the build on a non-zero code). One test fails on purpose to show what a failure looks like; the fix is the task.
Gst.phptests.php
REAL RUN
✍ Try it yourself The last test fails on purpose. Work out the right total by hand and fix the expected value.
999 x 12% = 119.88, so the total is 1118.88. The code is right and the test is wrong: change 1118.8 to 1118.88 and all 7 pass (exit code 0).
Complete PHP 8.3 Course  |  Part 5  |  Composer, REST APIs & Testing
M19Check your understanding

Quick Quiz

Click an answer. Wrong answers shake; the right one turns green and explains why.

Q1. Which status code should a successful POST that created a record return?
✔ 201 Created, ideally with a Location header.
Q2. How do you read a JSON request body in PHP?
✔ Then json_validate and json_decode.
Q3. What does composer dump-autoload create?
✔ One require replaces all manual requires.
🎯
Your score: 0 / 3 (first try counts)
Answer all questions. Discuss any wrong answer with your partner before moving on.
Complete PHP 8.3 Course  |  Part 5  |  Composer, REST APIs & Testing
M19Module summary

Recap: Composer, REST APIs & Testing

What you learned in M19

  • ✔Composer: composer.json + PSR-4 autoload; require vendor/autoload.php once.
  • ✔Packages come from Packagist with composer require; never commit vendor/.
  • ✔REST: nouns in URLs, HTTP methods for actions, correct status codes, JSON both ways.
  • ✔Front controller + router; php://input + json_validate for JSON bodies.
  • ✔422 with field errors, 401/403 for keys, meta for pagination.
  • ✔Tests check rules automatically; PHPUnit is the standard tool.
🏆

Module 19 complete!

You practised 10 real examples.

👉 Coming next

M20 Capstone Projects, Deployment & Career: choose a project, deploy it on real hosting, plan your PHP career and get your certificate.
Complete PHP 8.3 Course  |  Part 5  |  Composer, REST APIs & Testing
M20

Capstone Projects, Deployment & Career

Time to build something real. Pick a capstone project, plan it, put it on Git, deploy it to real hosting, and plan your next steps as a PHP developer in Jharkhand, Bihar or remotely.

  • Choosing and planning a project
  • Git, GitHub and a good README
  • Deploying to shared hosting (cPanel) and a VPS
  • Production settings and a go-live checklist
  • Next step: Laravel
  • Career roadmap and your certificate
YOU WILL BUILD:
10 mini projects to extendYour own portfolio projectYour course certificate
🎓
Part 5  •  about 5 hours
10 practice examples: 5 Easy • 3 Medium • 2 Hard
Complete PHP 8.3 Course  |  BrainBit Infotech, Ranchi
M20Where is this used in real work?

What a finished PHP project looks like

https://vidyacoaching.in/admin
248
students
₹3.2L
fees this month
91%
attendance
12
dues pending

Live on HTTPS • MySQL backups every night • GitHub repository with README • used daily by the office staff.

🎯

A project gets you hired

Employers and clients ask "show me something you built". One complete, deployed project beats ten certificates.
💼

Local demand

Schools, coaching centres, clinics, shops and NGOs in Ranchi, Jamshedpur, Dhanbad and Patna need exactly these systems.
🌐

Remote too

PHP, WordPress and Laravel work is posted daily on LinkedIn, Upwork and company career pages.
Complete PHP 8.3 Course  |  Part 5  |  Capstone Projects, Deployment & Career
M20Projects

Choose your capstone

LevelProjectSkills usedGood for
EasyPortfolio + contact form, Notice board, To-do list, Online quiz, GuestbookM1-M11, files or one tablefirst project, school students
MediumLibrary management, Hostel/PG booking, Shopping cart with checkoutCRUD, sessions, transactionscollege project, first freelance work
HardCoaching institute ERP, Blog CMS with admin panelauth, roles, reports, uploads, APIjob portfolio, real client delivery

📝 Week 1: plan

users, pages, tables (draw them), must-have vs nice-to-have list

💻 Weeks 2-3: build

one feature at a time; commit to Git after each; test with real data

🚀 Week 4: ship

deploy, write the README, record a 2-minute demo video, show it to a real user

The next 10 slides give a small working starter for every project. Extend the one you choose.

Complete PHP 8.3 Course  |  Part 5  |  Capstone Projects, Deployment & Career
M20Planning

Planning slide: fill this in for your project

1. Problem and users

Who uses it? (office staff, students, parents). What problem does it solve? What do they do today (register, Excel, WhatsApp)?

2. Pages

List every screen: login, dashboard, list, add, edit, report, settings. Draw rough boxes on paper.

3. Tables

Each noun is a table: students, courses, payments, attendance. Write the columns and types; mark primary and foreign keys.

4. Rules

Fee due dates, late fines, roles allowed per page, validations. These become functions and tests.

5. Security

password_hash, prepared statements, htmlspecialchars, CSRF tokens, role checks, upload checks.

6. Done means

Deployed on HTTPS, README with screenshots, sample data, backup plan, one real user has tried it.
Complete PHP 8.3 Course  |  Part 5  |  Capstone Projects, Deployment & Career
M20Git

Git, GitHub and a README

D:\projects\vidya-erp> git init
> git add .
> git commit -m "Student list and add form"
> git branch -M main
> git remote add origin https://github.com/you/vidya-erp.git
> git push -u origin main

.gitignore

vendor/
.env
uploads/*
storage/logs/*
Never commit secretsDatabase passwords and API keys go in .env (ignored). Commit a .env.example with blank values instead.

README.md checklist

  • Project name and one-line purpose
  • 3-4 screenshots
  • Features list
  • Tech: PHP 8.3, MySQL/MariaDB, (Composer)
  • Setup steps: clone, import database.sql, copy .env.example, run
  • Demo login (e.g. admin@demo.in / Demo@123)
  • Live link + your name and contact
Complete PHP 8.3 Course  |  Part 5  |  Capstone Projects, Deployment & Career
M20Animated explainer

Deploying to shared hosting (cPanel)

1

Buy hosting + domain

Choose PHP 8.3 (MultiPHP Manager / Select PHP Version). Point the domain to the host.
2

Create the database

cPanel → MySQL Databases: new DB + user with a strong password; add user to DB.
3

Import data

phpMyAdmin → Import your database.sql (export it from XAMPP's phpMyAdmin).
4

Upload files

File Manager → public_html: upload a zip and extract (or use Git / FTP).
5

Production config

Update DB name/user/password in .env or config. Keep config above public_html if possible.
6

php.ini settings

display_errors=Off, log_errors=On, correct upload limits, timezone Asia/Kolkata.
7

HTTPS

SSL/TLS Status → run AutoSSL (free). Redirect http to https.
8

Test + backup

Test every page with real logins. Schedule database backups (cron / cPanel Backup).
Complete PHP 8.3 Course  |  Part 5  |  Capstone Projects, Deployment & Career
M20Deployment

Go-live checklist and going further

Before you give the link to a client

  • HTTPS works; http redirects to https
  • display_errors Off; errors go to a log file
  • No test accounts with weak passwords; admin password changed
  • All forms: validation, CSRF token, escaped output
  • All queries prepared; DB user has only needed rights
  • Uploads checked; uploads folder cannot run PHP
  • Daily database backup and a tested restore
  • Timezone Asia/Kolkata; dates look right
  • Works on a mobile phone

VPS (more control)

A VPS (cloud server) runs Ubuntu with Nginx or Apache + PHP-FPM 8.3 + MySQL. You manage updates, firewall and backups yourself. Used for bigger apps and Laravel projects.

Next: Laravel

Laravel gives you routing, Eloquent ORM (models), Blade templates, migrations, validation, auth scaffolding and queues. Everything you built by hand in M17-M19 maps directly to a Laravel feature, which makes it easy to learn now.
Complete PHP 8.3 Course  |  Part 5  |  Capstone Projects, Deployment & Career
M20Practice 1 of 10  •  Easy

Example 1: Personal portfolio with contact form

● Easy💼 Real project: Your own website for jobs and freelancing
A one-page portfolio: projects come from an array (later from MySQL), and the contact form validates and saves messages with PRG.
index.php
REAL RUN
✍ Try it yourself Add a "Download CV" link and a skills section with progress bars.
Skills array => percent; print
.
Complete PHP 8.3 Course  |  Part 5  |  Capstone Projects, Deployment & Career
M20Practice 2 of 10  •  Easy

Example 2: Notice board

● Easy💼 Real project: School and society notice boards
Notices stored in a JSON file: newest first, important ones highlighted, and a small add form for the office (escape on output).
notices.phpnotices.json
REAL RUN
✍ Try it yourself Add an expiry date: hide notices older than 30 days.
Store a Y-m-d date and filter with strtotime($n['date']) >= strtotime('-30 days').
Complete PHP 8.3 Course  |  Part 5  |  Capstone Projects, Deployment & Career
M20Practice 3 of 10  •  Easy

Example 3: To-do list (sessions)

● Easy💼 Real project: Personal task apps
Tasks live in the session: add, mark done and clear completed. Each action is a POST followed by a redirect.
todo.php
REAL RUN
✍ Try it yourself Save tasks in a MySQL table so they survive closing the browser.
Create a tasks table (id, text, done) and replace the session array with SELECT / INSERT / UPDATE.
Complete PHP 8.3 Course  |  Part 5  |  Capstone Projects, Deployment & Career
M20Practice 4 of 10  •  Easy

Example 4: Online quiz

● Easy💼 Real project: Practice tests for schools and coaching
Questions from an array, one form, instant scoring with the correct answers shown. Shuffle the options so neighbours cannot copy positions.
quiz.php
REAL RUN
✍ Try it yourself Load questions from a MySQL table and save each student's score with the date.
Tables questions(id, text, opt_a..opt_c, answer) and attempts(student, score, taken_at).
Complete PHP 8.3 Course  |  Part 5  |  Capstone Projects, Deployment & Career
M20Practice 5 of 10  •  Easy

Example 5: Guestbook (MySQL)

● Easy💼 Real project: Visitor feedback on event or tourism sites
A first MySQL project: one table, a form with validation, a prepared INSERT and a list of the latest entries.
guestbook.php
REAL RUN
✍ Try it yourself Add a star rating (1-5) and show the average rating at the top.
Add a rating TINYINT column, a select box, and SELECT AVG(rating).
Complete PHP 8.3 Course  |  Part 5  |  Capstone Projects, Deployment & Career
M20Practice 6 of 10  •  Medium

Example 6: Library management

● Medium💼 Real project: School and college libraries
Issue and return with rules enforced in SQL: a book must be available, a member may hold at most 2 books, and a fine of Rs 2/day is charged after 14 days. Each action is checked and recorded.
library.php
REAL RUN
✍ Try it yourself Add a report of members with unpaid fines.
SELECT member_id, SUM(fine) FROM loans WHERE fine > 0 AND paid = 0 GROUP BY member_id.
Complete PHP 8.3 Course  |  Part 5  |  Capstone Projects, Deployment & Career
M20Practice 7 of 10  •  Medium

Example 7: Hostel / PG booking

● Medium💼 Real project: Hostel, PG and guest-house booking
A booking is accepted only if the bed is free for the requested dates. The overlap test start < other_end AND end > other_start runs inside a transaction with FOR UPDATE so two people cannot book the same bed at the same moment.
book.php
REAL RUN
✍ Try it yourself Add a function that lists free beds for a date range.
SELECT id FROM beds WHERE id NOT IN (SELECT bed_id FROM bookings WHERE check_in < :to AND check_out > :from).
Complete PHP 8.3 Course  |  Part 5  |  Capstone Projects, Deployment & Career
M20Practice 8 of 10  •  Medium

Example 8: E-commerce cart with checkout

● Medium💼 Real project: Online shops for local businesses
The cart is in the session; checkout runs a transaction that creates the order, adds order items, and reduces stock only if enough is available. The first checkout fails (only 3 paintings in stock), so nothing is saved; after changing the quantity it succeeds. The order is #2 because MySQL does not reuse the id used by the rolled-back attempt. Check the Database tab.
shop.php
REAL RUN
✍ Try it yourself Add a coupon field at checkout (FIRST50 = Rs 50 off) and store the discount in orders.
Add a discount column; compute it before UPDATE orders SET total.
Complete PHP 8.3 Course  |  Part 5  |  Capstone Projects, Deployment & Career
M20Practice 9 of 10  •  Hard

Example 9: Coaching institute ERP dashboard

● Hard💼 Real project: A real client project: coaching centre management
The dashboard of an ERP: total students, fees collected this month, attendance percentage and a list of pending dues, each from one SQL query. A CSS bar chart shows monthly collection.
dashboard.php
REAL RUN
✍ Try it yourself Add a "Send reminder" button next to each due that records a reminder in a table.
A small POST form per row with the student id and a CSRF token; INSERT INTO reminders.
Complete PHP 8.3 Course  |  Part 5  |  Capstone Projects, Deployment & Career
M20Practice 10 of 10  •  Hard

Example 10: Blog CMS with admin panel

● Hard💼 Real project: Content websites for schools, NGOs and businesses
Public pages list posts by slug; the admin (password_hash login) creates posts with automatic slugs and a CSRF-protected form. Drafts are hidden from the public. This is the core of what WordPress does.
index.phpadmin.php
REAL RUN
✍ Try it yourself Add edit and delete for posts, and an image upload for each post.
Reuse the CRUD pattern from M17 and the safe upload function from M12.
Complete PHP 8.3 Course  |  Part 5  |  Capstone Projects, Deployment & Career
M20Career

Your PHP career roadmap

🌱 Now (0-3 months)

  • Finish 2 capstones and deploy one
  • GitHub profile with READMEs
  • LinkedIn: "PHP Developer (Fresher), Ranchi"
  • Practise SQL and logic daily

💼 First work

  • Internships with local IT firms and startups in Ranchi, Jamshedpur, Patna, Kolkata
  • Small freelance sites for schools, clinics, shops
  • WordPress customisation jobs

🚀 Grow (6-18 months)

  • Laravel + REST APIs
  • Git teamwork, code reviews
  • Basic Linux server, deployment
  • JavaScript (fetch) or Vue/React for front ends

🏆 Roles

  • PHP / Laravel Developer
  • Full-stack Developer
  • WordPress Developer
  • Back-end / API Developer
  • Remote roles via LinkedIn, Upwork, company sites
Hackathons and communityJoin college hackathons, Smart India Hackathon (team entries), and online PHP/Laravel communities. Build in public: post your project progress weekly.
Interview topics from this courseOOP and interfaces, SQL joins and GROUP BY, prepared statements, sessions vs cookies, password hashing, REST status codes, PHP 8 features (match, enums, readonly, named arguments).
Complete PHP 8.3 Course  |  Part 5  |  Capstone Projects, Deployment & Career
M20Congratulations!

Certificate of Completion

BRAINBIT INFOTECH, RANCHI

Certificate of Completion

This is to certify that

Your Name Here

has successfully completed the Complete PHP 8.3 Course (Beginner to Advanced)
20 modules • 200 practical examples • about 91 class hours

Date: ____________
🏅
Nandan Kumar
Founder & Head of Training
Click the name and date to edit, then print.
Complete PHP 8.3 Course  |  Part 5  |  Capstone Projects, Deployment & Career
M20Check your understanding

Quick Quiz

Click an answer. Wrong answers shake; the right one turns green and explains why.

Q1. Where should database passwords live in a project?
✔ Commit .env.example with blank values instead.
Q2. What should display_errors be on a live site?
✔ Visitors must never see paths, SQL or stack traces.
Q3. What prevents two people booking the same bed at the same moment?
✔ The row lock makes the second booking wait, then see the clash.
🎯
Your score: 0 / 3 (first try counts)
Answer all questions. Discuss any wrong answer with your partner before moving on.
Complete PHP 8.3 Course  |  Part 5  |  Capstone Projects, Deployment & Career
M20Module summary

Recap: Capstone Projects, Deployment & Career

What you learned in M20

  • ✔Pick a capstone at your level; plan users, pages, tables, rules and security first.
  • ✔Commit often; a clear README with screenshots and setup steps.
  • ✔Deploy: PHP 8.3 on hosting, new DB user, import SQL, upload files, update config.
  • ✔Production: display_errors Off, logs on, HTTPS, backups, strong admin passwords.
  • ✔Learn Laravel next: it automates everything you built by hand.
  • ✔Build, deploy, share. Your projects are your CV.
🏆

Module 20 complete!

You practised 10 real examples.

👉 Coming next

Congratulations on completing the course! Keep building: one small feature every day.
Complete PHP 8.3 Course  |  Part 5  |  Capstone Projects, Deployment & Career
1 / 1

✎ Code Lab