Build real web pages: templates, query strings, forms with validation, sessions, cookies, uploads and HTTP.
9
PHP Pages, Templates & Query Strings
10 examples • 4 h
10
Forms & Validation
10 examples • 5 h
11
Sessions & Cookies
10 examples • 5 h
12
Uploads, Headers & HTTP
10 examples • 4 h
🐘
<?php
PHP 8.3 • MySQL • XAMPP
BrainBit Infotech, Ranchi | Complete PHP 8.3 Course | Keys: ← → navigate M menu L Code Lab F fullscreen
M9
PHP Pages, Templates & Query Strings
Now PHP meets the browser for real. You will build multi-page websites with a shared header and footer, read values from the URL, and protect pages from attacks.
The request/response cycle
Templates with the alternative syntax
include and require for layouts
Superglobals: $_GET, $_SERVER and friends
htmlspecialchars and XSS protection
A simple router and pagination links
YOU WILL BUILD: Course detail pagesSearch filter by cityMulti-page school websiteXSS attack and fix
🌐
Part 3 • about 4 hours 10 practice examples: 5 Easy • 3 Medium • 2 Hard
Everything from the user is a string and untrusted$_GET['id'] is "3", not 3, and could be anything an attacker types. Convert with (int) or filter_input(), and always escape output.
● Medium💼 Real project: Filters on job portals and property sites
A GET form puts the choice in the URL (?city=Ranchi&q=php), so the result page can be bookmarked and shared. array_filter does the filtering; the form keeps the selected values.
jobs.php
REAL RUN
✍ Try it yourself Add a "Remote" job and a checkbox "Remote only".
Add a 4th field true/false; read $_GET['remote'] ?? '' and filter on it.
● Medium💼 Real project: Long lists: products, results, news
Show 4 items per page. array_slice picks the items for the current page; ceil gives the number of pages; links keep other filters with http_build_query.
news.php
REAL RUN
✍ Try it yourself Change to 3 per page. What happens with ?page=100 or ?page=-5?
max(1, min($pages, ...)) clamps the value, so it shows the last or first page.
Example 9: Multi-page school website with a router
● Hard💼 Real project: Small business and school websites
A front controller: every link goes to index.php?page=.... A whitelist maps pages to files in pages/; the layout wraps whichever page is chosen; unknown pages get a 404 page.
● Hard💼 Real project: Security review of any page that shows user input
The same attack link is sent to two pages. unsafe.php prints the input as it is (vulnerable on purpose, look at the Request tab: the script tag is in the HTML). safe.php escapes it. The recorded page view does not run scripts, but a real browser would.
unsafe.phpsafe.php
REAL RUN
✍ Try it yourself Try the attack " onmouseover="alert(1) inside an input value. Why does ENT_QUOTES matter?
Without escaping quotes, the attacker closes value="..." and adds an event attribute. ENT_QUOTES escapes both " and '.
Forms are how users talk to your website: contact, admission, feedback, payment. You will receive form data with PHP, check it properly and respond the professional way.
HTML form tags explained
GET vs POST
Reading $_POST and form arrays
Validation with trim, filter_var and regex
Sticky forms and error messages
Post/Redirect/Get and CSRF tokens
YOU WILL BUILD: Contact formBMI calculatorAdmission form with validationFee receipt generator
📝
Part 3 • about 5 hours 10 practice examples: 5 Easy • 3 Medium • 2 Hard
Student nameIshita KumariMobile98350Mobile must be 10 digits starting with 6-9ClassClass 6 ▾
Submit
📋
Admissions and registrations
Schools, coaching centres, events and job portals all collect details through forms processed by PHP.
✅
Validation protects data
A missing mobile number or a wrong email means a lost admission. PHP checks every field on the server.
🛡️
Never trust the browser
Browser checks (required, type="email") can be removed by anyone. Server-side validation in PHP is the real gatekeeper.
Complete PHP 8.3 Course | Part 3 | Forms & Validation
M10Concept
HTML form basics
<form method="post" action="save.php">: where and how to send
Every input needs a name: it becomes the key in $_POST
Types: text, email, tel, number, date, password, hidden, plus <select>, <textarea>, radio and checkbox
No action = send to the same page (common in PHP)
$_SERVER['REQUEST_METHOD'] === 'POST' tells you the form was submitted
Two steps in the Browser tabStep 1: the empty form (GET). Step 2: the user typed and clicked the button (POST). The yellow bar shows exactly what was sent.
hello.php
REAL RUN
Complete PHP 8.3 Course | Part 3 | Forms & Validation
M10Animated explainer
GET vs POST
GET
GET /search.php?q=php&city=Ranchi
Data is in the URL (visible, bookmarkable, in history)
Limited length
Should not change anything on the server
Use for: search, filters, pagination
POST
POST /register.php Content-Type: application/x-www-form-urlencoded name=Ishita&mobile=9835012345&password=*****
Data is in the request body, not the URL
No size problem; allows file uploads
Used when something is created or changed
Use for: login, registration, payments, uploads
POST is not encryptionAnyone on the network can read POST data on plain http. Real sites use https so everything is encrypted.
Complete PHP 8.3 Course | Part 3 | Forms & Validation
Collect errors in an array $errors['field'] = 'message'. Save only when the array is empty.
validate.php
REAL RUN
Complete PHP 8.3 Course | Part 3 | Forms & Validation
M10Animated explainer
Post/Redirect/Get: no more double submissions
❌ Without PRG
POST /fee.php➤200: "Paid Rs 1500"
User presses F5 / Refresh: "Confirm Form Resubmission?" → clicks Continue → paid twice!
✅ With PRG
POST /fee.php➤save➤302 Location: thanks.php
GET /thanks.php➤200: "Paid Rs 1500"
Refresh now only repeats the harmless GET. Nothing is saved twice.
header('Location: thanks.php?id=' . $id); exit; // always exit after a redirect
Complete PHP 8.3 Course | Part 3 | Forms & Validation
M10Practice 1 of 10 • Easy
Example 1: Contact form
● Easy💼 Real project: Contact pages of every business website
The classic form: show it on GET, process it on POST. Messages are appended to messages.txt (see the Files tab). Output is escaped.
contact.php
REAL RUN
✍ Try it yourself Add a mobile field and save it in the file too.
Add , read $_POST['mobile'] and include it in the line.
Complete PHP 8.3 Course | Part 3 | Forms & Validation
M10Practice 2 of 10 • Easy
Example 2: BMI calculator form
● Easy💼 Real project: Health and fitness websites
A form that calculates instead of saving. Inputs are type="number"; PHP converts with (float) and shows the result on the same page.
bmi.php
REAL RUN
✍ Try it yourself Show a colour: green for Normal, orange for Overweight, red for others.
Use another match on $label to choose a colour and put it in style="color:...".
Complete PHP 8.3 Course | Part 3 | Forms & Validation
M10Practice 3 of 10 • Easy
Example 3: Feedback with radio buttons
● Easy💼 Real project: Course and service feedback
Radio buttons with the same name send only the chosen value. We check it is one of the allowed values with in_array.
feedback.php
REAL RUN
✍ Try it yourself What if someone edits the HTML and sends rating=99? Try it in the Request idea below.
array_key_exists fails, so "Invalid rating" shows. That is why we check on the server.
Complete PHP 8.3 Course | Part 3 | Forms & Validation
M10Practice 4 of 10 • Easy
Example 4: Course selection with checkboxes
● Easy💼 Real project: Choosing subjects, toppings, add-ons
Name checkboxes with [] (name="courses[]") and PHP receives an array. We keep only known values and add up the fees.
select.php
REAL RUN
✍ Try it yourself Give 15% off if all 4 courses are chosen.
Use match(true) on count($picked): 4 => 0.85, 3 => 0.9, default => 1.
Complete PHP 8.3 Course | Part 3 | Forms & Validation
M10Practice 5 of 10 • Easy
Example 5: Calculator form
● Easy💼 Real project: Quick tools on websites (EMI, GST, unit converters)
Two numbers and an operator from a select box. match does the maths; dividing by zero is handled.
calc.php
REAL RUN
✍ Try it yourself Add a % operator (remainder) and a power operator.
Add '%' => $a % $b and '^' => $a ** $b to the list and the match.
Complete PHP 8.3 Course | Part 3 | Forms & Validation
M10Practice 6 of 10 • Medium
Example 6: Admission form with validation
● Medium💼 Real project: School and college admission portals
Every field is checked on the server. Errors appear next to each field in red, and nothing is saved until all fields are valid.
admission.php
REAL RUN
✍ Try it yourself Add a date of birth field: the student must be between 10 and 18 years old.
Use DateTimeImmutable and ->diff(new DateTimeImmutable())->y.
Complete PHP 8.3 Course | Part 3 | Forms & Validation
M10Practice 7 of 10 • Medium
Example 7: Sticky registration form
● Medium💼 Real project: Long forms where users must not retype everything
"Sticky" means fields keep what the user typed after an error. Passwords are the exception: never send them back to the browser.
register.php
REAL RUN
✍ Try it yourself Why do we not refill the password fields? Add a "Show password" hint instead.
Sending passwords back in HTML exposes them in page source and browser caches.
Complete PHP 8.3 Course | Part 3 | Forms & Validation
M10Practice 8 of 10 • Medium
Example 8: Post/Redirect/Get with thank-you page
● Medium💼 Real project: Payments, orders and bookings
After saving, the page redirects (302) to a thank-you page with the receipt number. Watch the Browser steps: POST, then the redirect, then a GET. Refreshing the last page is now harmless.
pay.phpthanks.phppayments.csv
REAL RUN
✍ Try it yourself Press "refresh" on thanks.php (run that request twice). How many lines are in payments.csv?
Still one: refreshing repeats only the GET of thanks.php, not the POST.
Complete PHP 8.3 Course | Part 3 | Forms & Validation
M10Practice 9 of 10 • Hard
Example 9: Multi-step application form
● Hard💼 Real project: Scholarship and job applications
A long form split into steps. Earlier answers travel in hidden fields, the step number decides what to show, and the last step shows a summary. (Module 11 shows a cleaner way with sessions.)
apply.php
REAL RUN
✍ Try it yourself Add a 4th step "Family income" between school and confirm.
Add a step to $steps, a new elseif block, and change "of 3" and 33% to use count($steps).
Complete PHP 8.3 Course | Part 3 | Forms & Validation
M10Practice 10 of 10 • Hard
Example 10: Fee receipt generator form
● Hard💼 Real project: Fee counters in schools and coaching centres
The clerk fills a form; PHP validates it, calculates late fee and GST, then prints a printable receipt with an amount in words (a small recursive function).
receipt.php
REAL RUN
✍ Try it yourself The late fee line is hard to read. Rewrite it with a helper function lateDays($due, $today).
Return 0 when $today <= $due, else the diff days. Then $late = lateDays(...) * 10.
Complete PHP 8.3 Course | Part 3 | Forms & Validation
M10Check your understanding
Quick Quiz
Click an answer. Wrong answers shake; the right one turns green and explains why.
Q1. How does PHP receive <input name="city"> from a POST form?
✔ POST forms fill $_POST.
Q2. Why redirect after saving a form (PRG)?
✔ The last request becomes a harmless GET.
Q3. Where must validation happen?
✔ Browser checks can be bypassed; PHP checks cannot.
🎯
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 3 | Forms & Validation
M10Module summary
Recap: Forms & Validation
What you learned in M10
✔Forms send name=value pairs; every input needs a name.
✔GET for searching (URL), POST for saving (body); always use HTTPS live.
✔Validate on the server: trim, filter_var, regex, in_array; collect errors per field.
✔Sticky forms refill values (never passwords) and show errors next to fields.
✔Checkbox groups use name="x[]" and arrive as arrays.
✔Post/Redirect/Get stops double submissions: header("Location: ...") then exit.
🏆
Module 10 complete!
You practised 10 real examples.
👉 Coming next
M11 Sessions & Cookies: remember users across pages: logins, carts, language and flash messages.
Complete PHP 8.3 Course | Part 3 | Forms & Validation
M11
Sessions & Cookies
HTTP forgets everything after each request. Cookies and sessions let your site remember who is logged in, what is in the cart and which language the user prefers.
Why HTTP is stateless
Cookies: setcookie, $_COOKIE, expiry, httponly
Sessions: session_start and $_SESSION
Login state and logout
Flash messages
Session security: regenerate the id
YOU WILL BUILD: Page view counterLogin and logoutShopping cartQuiz across pages
🍪
Part 3 • about 5 hours 10 practice examples: 5 Easy • 3 Medium • 2 Hard
Complete PHP 8.3 Course | Part 3 | Sessions & Cookies
M11Practice 4 of 10 • Easy
Example 4: Language choice (Hindi / English)
● Easy💼 Real project: Bilingual government and school portals
Text for each language lives in an array. The choice is kept in the session; a small function t() returns the right text.
index.php
REAL RUN
✍ Try it yourself Add Bengali (bn) as a third language.
Add 'bn' to the in_array list, to $T, and a link.
Complete PHP 8.3 Course | Part 3 | Sessions & Cookies
M11Practice 5 of 10 • Easy
Example 5: Flash message
● Easy💼 Real project: "Saved successfully" banners after actions
A flash message is stored in the session, shown once on the next page, then deleted. Combined with redirect (PRG) it is the standard way to confirm actions.
save.phplist.php
REAL RUN
✍ Try it yourself Make a helper flash($type, $msg) and show error flashes in red.
Store type; pick a colour with match ($flash['type']).
Complete PHP 8.3 Course | Part 3 | Sessions & Cookies
M11Practice 6 of 10 • Medium
Example 6: Login and logout (hard-coded user)
● Medium💼 Real project: Admin panels of small websites
A first login system. The password is checked with password_verify against a stored hash (never plain text). The session remembers the user; the dashboard redirects guests back to login. A full MySQL version comes in Module 18.
login.phpdashboard.phplogout.php
REAL RUN
✍ Try it yourself Add a second user "office" with its own password and show the role on the dashboard.
Store ['hash' => ..., 'role' => 'staff'] per user and save the role in the session.
Complete PHP 8.3 Course | Part 3 | Sessions & Cookies
M11Practice 7 of 10 • Medium
Example 7: Shopping cart in a session
● Medium💼 Real project: E-commerce carts
The cart is an array in $_SESSION: product id → quantity. Add and remove links change it; the page recalculates the total every time.
shop.php
REAL RUN
✍ Try it yourself Add an "Empty cart" link and a delivery charge of Rs 30 under Rs 200.
Complete PHP 8.3 Course | Part 3 | Sessions & Cookies
M11Practice 8 of 10 • Medium
Example 8: Quiz across pages with score
● Medium💼 Real project: Online tests and quizzes
One question per page. The current question number and score live in the session, so the user cannot skip ahead by changing the URL.
quiz.php
REAL RUN
✍ Try it yourself Add a 30-second time limit for the whole quiz.
Store $s['started'] = time() at the start; at the end compare time() - started.
Complete PHP 8.3 Course | Part 3 | Sessions & Cookies
M11Practice 9 of 10 • Hard
Example 9: Members-only area with guard and timeout
● Hard💼 Real project: Student and staff portals
A reusable guard.php is required at the top of every private page: it checks login, role and inactivity (here 10 seconds for the demo; real sites use about 15-30 minutes).
guard.phplogin.phpmarks.phpwait.php
REAL RUN
✍ Try it yourself Make TIMEOUT 15 minutes and show "Session expires in X minutes" on the page.
Complete PHP 8.3 Course | Part 3 | Sessions & Cookies
M11Practice 10 of 10 • Hard
Example 10: Recently viewed products
● Hard💼 Real project: "Recently viewed" strips on shopping sites
A capped list of the last 4 products in a cookie (JSON). Viewing a product moves it to the front; duplicates are removed. Only ids are stored; names come from the server.
product.php
REAL RUN
✍ Try it yourself Add a "Clear history" link that deletes the cookie.
setcookie('recent', '', time() - 3600); and reset $recent = [].
Complete PHP 8.3 Course | Part 3 | Sessions & Cookies
M11Check your understanding
Quick Quiz
Click an answer. Wrong answers shake; the right one turns green and explains why.
Q1. Where is session data stored?
✔ That is why sessions are safer than cookies for login data.
Q2. What must come before any HTML output?
✔ They send HTTP headers, which must go first.
Q3. When should you call session_regenerate_id(true)?
✔ It stops session fixation attacks.
🎯
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 3 | Sessions & Cookies
M11Module summary
Recap: Sessions & Cookies
What you learned in M11
✔HTTP is stateless; cookies and sessions add memory.
✔setcookie() sends a cookie; $_COOKIE reads it on the next request; users can edit cookies.
✔session_start() + $_SESSION keep data on the server, linked by the PHPSESSID cookie.
✔Logout: empty $_SESSION and session_destroy().
✔Flash messages: store, redirect, show once, unset.
✔Security: regenerate id at login, httponly/secure/samesite cookies, inactivity timeout.
🏆
Module 11 complete!
You practised 10 real examples.
👉 Coming next
M12 Uploads, Headers & HTTP: photo and document uploads, downloads, status codes, JSON responses and calling other APIs.
Complete PHP 8.3 Course | Part 3 | Sessions & Cookies
M12
Uploads, Headers & HTTP
Real websites accept photos and documents, send files for download, return the right status codes and talk to other services. This module covers the HTTP side of PHP.
File uploads: enctype, $_FILES, upload errors
Safe uploads: size, extension, real MIME type, new name
header(): redirects, content types, downloads
HTTP status codes and http_response_code()
Sending JSON responses
Calling other APIs with file_get_contents and cURL
YOU WILL BUILD: Profile photo uploadReceipt downloadJSON endpointDocument upload portal
📤
Part 3 • about 4 hours 10 practice examples: 5 Easy • 3 Medium • 2 Hard
Limits are in php.ini: upload_max_filesize and post_max_size. XAMPP's defaults are generous; these slides were recorded with 2M. Your own code should apply a stricter limit for each field.
● Easy💼 Real project: Profile pictures on any portal
The minimum working upload: the form, a check that there was no error, and move_uploaded_file to the uploads folder. (Example 6 adds the full safety checks.)
upload.php
REAL RUN
✍ Try it yourself Show the uploaded photo on the page with an <img> tag.
<img src="<?= $new ?>" width="120"> (only after a successful upload).
● Medium💼 Real project: Every upload form on a live site
The safe version: check the error code, our own size limit (200 KB), the extension, and the real MIME type with finfo. A PHP script renamed to .jpg and a 2 MB file are both rejected.
photo.php
REAL RUN
✍ Try it yourself Also reject images smaller than 200 x 200 pixels.
After getimagesize: if ($w < 200 || $h < 200) return 'Photo too small';
● Medium💼 Real project: Bulk upload of students or products
The office uploads a CSV instead of typing 200 rows. PHP reads the uploaded temp file directly with fgetcsv, validates each row and reports how many were imported.
import.php
REAL RUN
✍ Try it yourself Also skip duplicate mobile numbers.
Keep $seen[$row['mobile']] = true and skip if already set.
● Medium💼 Real project: Professional error pages on live sites
A front controller sends the right status code and a friendly page. A set_exception_handler catches crashes, logs the details and shows a polite 500 page without exposing code.
index.phperrors/404.phperrors/500.php
REAL RUN
✍ Try it yourself Add a 403 page for ?p=admin.
Add 'admin' => fn() => ... that sets http_response_code(403) and requires errors/403.php.
● Hard💼 Real project: Weather, PIN-code and payment APIs
cURL sends an HTTP request from PHP and reads the JSON answer, with a timeout so a slow API cannot hang your site. The build machine had no internet, so a stand-in API on the same server returns sample values in the real Open-Meteo JSON format.
weather.phpstandin/forecast.php
REAL RUN
✍ Try it yourself Point $base to the real Open-Meteo URL on a computer with internet. What changes in your code?
Only $base changes to https://api.open-meteo.com/v1/forecast. Same JSON keys, so the template stays the same.
● Hard💼 Real project: Government job and scholarship portals
Several documents, each with its own rules (type, max size). A rules array drives the validation; files get safe random names inside a per-applicant folder, and a JSON manifest records what was stored.
documents.php
REAL RUN
✍ Try it yourself Add an "Aadhaar card (PDF, max 500 KB)" document. How many lines of code do you need?
One line in $rules. The form, validation and messages all come from the rules array.