PART 3 of 5  •  about 18 class hours

PHP for the Web

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
Complete PHP 8.3 Course  |  BrainBit Infotech, Ranchi
M9Where is this used in real work?

One PHP template, thousands of pages

brainbit-teaching.com/course.php?id=3
BrainBit InfotechHome | Courses | Contact

PHP & MySQL Full Stack

4 months • Rs 12,000 • Batch starts 1 Dec

Same file, different idcourse.php?id=1, ?id=2, ?id=3 ... one template shows every course. The header and footer come from header.php and footer.php.
🔗

Query strings

Product pages, search results, filters and pagination all read values from the URL with $_GET.
🧱

Layouts

Every page of a site shares one header, menu and footer through include. Change the menu once, every page updates.
🛡️

Safe output

Every value shown on a page passes through htmlspecialchars so attackers cannot inject scripts.
Complete PHP 8.3 Course  |  Part 3  |  PHP Pages, Templates & Query Strings
M9Animated explainer

The request/response cycle with a query string

💻
Browserclicks "PHP course"
GET /course.php?id=3
▶
$_GET = ['id' => '3'];
◀
200 OK • text/html
<h1>PHP & MySQL Full Stack</h1>...
course.php
waiting for a request
Complete PHP 8.3 Course  |  Part 3  |  PHP Pages, Templates & Query Strings
M9Concept

Templates: PHP inside HTML, the clean way

  • Do the work (variables, loops over data) at the top; keep HTML at the bottom.
  • Use <?= ?> to print and the alternative syntax for control flow: if (): ... endif;, foreach (): ... endforeach;
  • It reads like HTML, so designers can edit it too.
Browser tabThe real page PHP produced, shown at 80% size. The Request tab shows the raw HTML that was sent.
courses.php
REAL RUN
Complete PHP 8.3 Course  |  Part 3  |  PHP Pages, Templates & Query Strings
M9Concept

include and require: one header for every page

StatementIf the file is missing
includewarning, page continues
requirefatal error, page stops
include_once / require_oncesame, but never loads a file twice
  • Use require for essentials (config, database, functions).
  • The included file can use the variables of the page (e.g. $title).
  • Use __DIR__ . '/partials/header.php' so paths work from any folder.
about.phppartials/header.phppartials/footer.php
REAL RUN
Complete PHP 8.3 Course  |  Part 3  |  PHP Pages, Templates & Query Strings
M9Concept

Superglobals: data PHP gives every page

ArrayContains
$_GETquery string values
$_POSTform data (Module 10)
$_SERVERrequest info: method, URI, IP, browser
$_COOKIE / $_SESSIONremembered data (Module 11)
$_FILESuploaded files (Module 12)
$_ENVenvironment settings
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.
info.php
REAL RUN
Complete PHP 8.3 Course  |  Part 3  |  PHP Pages, Templates & Query Strings
M9Animated explainer

XSS: why every output needs htmlspecialchars

search.php?q=<script>alert('hacked')</script>

❌ echo $_GET['q'];

The browser receives <script>... as real code and runs it. An attacker could steal cookies or change the page.

✅ echo htmlspecialchars($_GET['q']);

< becomes &lt;, > becomes &gt;, quotes are escaped. The browser shows the text; nothing runs.
localhost:8000/search.php
localhost says
hacked
localhost:8000/search.php
You searched for: <script>alert('hacked')</script>
Golden ruleEscape on output: <?= htmlspecialchars($x) ?>. Many teams make a short helper e($x).
Complete PHP 8.3 Course  |  Part 3  |  PHP Pages, Templates & Query Strings
M9Concept

Links with query strings and a tiny router

  • http_build_query(['page' => 2, 'city' => 'Ranchi']) builds page=2&city=Ranchi with correct encoding.
  • urlencode for one value (spaces become +).
  • A router: one index.php decides which page file to load from ?page=. A whitelist array stops users from loading any file they want.
Never include user input directlyinclude $_GET['page'] . '.php'; lets attackers load other files. Always check against a list of allowed pages.
index.php
REAL RUN
Complete PHP 8.3 Course  |  Part 3  |  PHP Pages, Templates & Query Strings
M9Practice 1 of 10  •  Easy

Example 1: Dynamic welcome page

● Easy💼 Real project: Home pages that change by time and date
The page greets by time of day and shows a different "thought of the day" each day using date('z') (day of the year) and %.
index.php
REAL RUN
✍ Try it yourself Add 2 more thoughts. Show a festival message if today is between 20 Oct and 5 Nov.
Compare date('m-d') with '10-20' and '11-05' as strings.
Complete PHP 8.3 Course  |  Part 3  |  PHP Pages, Templates & Query Strings
M9Practice 2 of 10  •  Easy

Example 2: Layout with header/footer includes

● Easy💼 Real project: Every multi-page website
Two pages share the same header and footer through require. The page sets $title and $active; the header uses them to highlight the current menu item.
index.phpcontact.phpinc/header.phpinc/footer.php
REAL RUN
✍ Try it yourself Add a "Gallery" page in 3 lines using the same header and footer.
Copy contact.php to gallery.php, set $title/$active, and add 'gallery' => 'gallery.php' to $menu.
Complete PHP 8.3 Course  |  Part 3  |  PHP Pages, Templates & Query Strings
M9Practice 3 of 10  •  Easy

Example 3: Greeting from ?name=

● Easy💼 Real project: Personalised links in SMS and emails
Links like ?name=Ritu&city=Patna personalise a page. We read with ?? for defaults and escape the output.
hello.php
REAL RUN
✍ Try it yourself Add &course=PHP to the link and show it on the page.
$course = $_GET['course'] ?? 'any course';
Complete PHP 8.3 Course  |  Part 3  |  PHP Pages, Templates & Query Strings
M9Practice 4 of 10  •  Easy

Example 4: Product list from an array

● Easy💼 Real project: Catalogue pages of small shops
A card grid printed from an array with foreach. Later the array will come from MySQL, and this template will not change at all.
products.php
REAL RUN
✍ Try it yourself Show a red "SALE" label on products above Rs 2,000.
2000): ?>SALE
Complete PHP 8.3 Course  |  Part 3  |  PHP Pages, Templates & Query Strings
M9Practice 5 of 10  •  Easy

Example 5: Show request info

● Easy💼 Real project: Debug pages and visitor analytics
$_SERVER tells you about the request: method, address, browser. Analytics tools record these values for each visit.
request.php
REAL RUN
✍ Try it yourself Show "You are on mobile" if the browser text contains "Mobile".
str_contains($_SERVER['HTTP_USER_AGENT'] ?? '', 'Mobile')
Complete PHP 8.3 Course  |  Part 3  |  PHP Pages, Templates & Query Strings
M9Practice 6 of 10  •  Medium

Example 6: Course detail page by ?id= with 404

● Medium💼 Real project: Product and article pages
One template, many pages. The id is converted to an int; an unknown id returns a real 404 status so search engines do not index broken pages.
course.php
REAL RUN
✍ Try it yourself Add a "Previous course" link and hide it on the first course.
<?php if ($id > 1): ?><a href="course.php?id=<?= $id - 1 ?>">&laquo; Previous</a><?php endif; ?>
Complete PHP 8.3 Course  |  Part 3  |  PHP Pages, Templates & Query Strings
M9Practice 7 of 10  •  Medium

Example 7: Search filter by ?city=

● 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.
Complete PHP 8.3 Course  |  Part 3  |  PHP Pages, Templates & Query Strings
M9Practice 8 of 10  •  Medium

Example 8: Pagination links

● 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.
Complete PHP 8.3 Course  |  Part 3  |  PHP Pages, Templates & Query Strings
M9Practice 9 of 10  •  Hard

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.
index.phplayout.phppages/home.phppages/admission.phppages/results.phppages/404.php
REAL RUN
✍ Try it yourself Add a "Gallery" page. Which two places must you change?
Create pages/gallery.php and add 'gallery' => 'Gallery' to $routes. The menu updates by itself.
Complete PHP 8.3 Course  |  Part 3  |  PHP Pages, Templates & Query Strings
M9Practice 10 of 10  •  Hard

Example 10: XSS attack and the fix

● 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 '.
Complete PHP 8.3 Course  |  Part 3  |  PHP Pages, Templates & Query Strings
M9Check your understanding

Quick Quiz

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

Q1. In page.php?id=7&lang=hi, how do you read 7?
✔ Query string values are in $_GET, as strings.
Q2. What happens if a required file is missing?
✔ include only warns; require stops.
Q3. Which function prevents XSS when printing user input?
✔ It converts < > & and quotes to safe entities.
🎯
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  |  PHP Pages, Templates & Query Strings
M9Module summary

Recap: PHP Pages, Templates & Query Strings

What you learned in M9

  • ✔Each page view is a request; PHP builds and returns HTML.
  • ✔Templates: logic at the top, HTML with <?= ?> and endif/endforeach below.
  • ✔require/include share headers, footers and config across pages.
  • ✔$_GET reads the query string; $_SERVER describes the request; all input is untrusted.
  • ✔htmlspecialchars on every output stops XSS.
  • ✔Routers use a whitelist; pagination uses array_slice + ceil + http_build_query.
🏆

Module 9 complete!

You practised 10 real examples.

👉 Coming next

M10 Forms & Validation: contact, admission and fee forms with POST, validation and the PRG pattern.
Complete PHP 8.3 Course  |  Part 3  |  PHP Pages, Templates & Query Strings
M10

Forms & Validation

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
Complete PHP 8.3 Course  |  BrainBit Infotech, Ranchi
M10Where is this used in real work?

Every website collects data through forms

admission.school.in/apply.php
Online Admission Form 2027-28PHP
Student nameIshita Kumari Mobile98350 Mobile must be 10 digits starting with 6-9 ClassClass 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
M10Concept

Validation: never trust input

CheckHow
Requiredtrim($v) === ''
Emailfilter_var($v, FILTER_VALIDATE_EMAIL)
Whole number in rangefilter_var($v, FILTER_VALIDATE_INT, ['options' => ['min_range' => 1, 'max_range' => 12]])
Patternpreg_match('/^[6-9]\d{9}$/', $v)
One of a listin_array($v, $allowed, true)

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  |  BrainBit Infotech, Ranchi
M11Where is this used in real work?

Sessions are why websites "remember" you

erp.school.in/dashboard.php
👋 Welcome back, Mrs. Tirkey (Teacher)PHP

Language: English | हिंदी  •  Cart: 0  •  Logout

Stored where?Example
Session (server)user_id = 17, role = teacher
Cookie (browser)PHPSESSID = 8f2c...; lang = en
🔒

Logins

After you log in, every page knows who you are because your session holds your user id.
🛒

Carts and wizards

Items you add to a cart, or answers in a multi-page form, live in the session until you finish.
🌐

Preferences

Language, theme and "remember me" choices are stored in cookies so they survive closing the browser.
Complete PHP 8.3 Course  |  Part 3  |  Sessions & Cookies
M11Animated explainer

How a session works

💻
Browser
🍪 PHPSESSID=8f2c1a
POST /login.php➤
⬅Set-Cookie: PHPSESSID=8f2c1a
GET /dashboard.php
Cookie: PHPSESSID=8f2c1a
➤
⬅"Welcome, Mrs. Tirkey"
PHP serverwaiting
📁 session files
sess_8f2c1a:
 user_id = 17
 name = "Mrs. Tirkey"
Complete PHP 8.3 Course  |  Part 3  |  Sessions & Cookies
M11Concept

Cookies: small notes kept by the browser

  • setcookie('lang', 'hi', time() + 86400 * 30) = keep for 30 days
  • Must be called before any output (it is an HTTP header).
  • Read on the next request with $_COOKIE['lang'].
  • Options: httponly (JavaScript cannot read it), secure (https only), samesite.
  • Delete: set an expiry in the past.
Users can edit cookiesNever store prices, roles or "is_admin=1" in a cookie. Store an id, and keep the real data on the server.
lang.php
REAL RUN
Complete PHP 8.3 Course  |  Part 3  |  Sessions & Cookies
M11Concept

Sessions in 3 lines

  1. 1
    session_start(); at the top of every page that needs the session (before any output).
  2. 2
    Read and write $_SESSION['key'] like a normal array.
  3. 3
    Logout: $_SESSION = []; session_destroy();
CookieSession
Storedin the browseron the server
User can edit?yesno (only the id)
Lastsuntil expiryuntil browser closes / timeout
Use forpreferenceslogin, cart, wizard
visits.php
REAL RUN
Complete PHP 8.3 Course  |  Part 3  |  Sessions & Cookies
M11Animated explainer

Session security: fixation and regenerate

😈 1. Attacker gets a session id

He opens the site and gets PHPSESSID=evil123.

📧 2. Tricks the victim

Sends a link that makes the victim's browser use the same id evil123.

🔓 3. Victim logs in

If the id stays the same, the attacker's browser is now logged in too!

✅ Fix: new id at login

session_regenerate_id(true); right after a successful login. The old id becomes useless.

More good habits

  • Cookie flags: httponly, secure, samesite=Lax
  • Log out after inactivity (store last activity time)
  • Full logout destroys the session and its cookie
Complete PHP 8.3 Course  |  Part 3  |  Sessions & Cookies
M11Practice 1 of 10  •  Easy

Example 1: Page view counter (session)

● Easy💼 Real project: Counting steps in a checkout or quiz
Each browser gets its own counter in its own session. The Request tab shows the PHPSESSID cookie travelling with every request.
counter.php
REAL RUN
✍ Try it yourself Show a message "You love this page!" after 5 views.
= 5): ?> ...
Complete PHP 8.3 Course  |  Part 3  |  Sessions & Cookies
M11Practice 2 of 10  •  Easy

Example 2: Remember theme (cookie)

● Easy💼 Real project: Dark mode settings
The chosen theme is saved in a cookie for a year, so the next visit opens in dark mode automatically, even after closing the browser.
theme.php
REAL RUN
✍ Try it yourself Add a third theme "sepia" (#f4ecd8 background, #5b4636 text).
Just add it to $themes; the rest works automatically.
Complete PHP 8.3 Course  |  Part 3  |  Sessions & Cookies
M11Practice 3 of 10  •  Easy

Example 3: Last visit time

● Easy💼 Real project: "Last login" notices in banking apps
A cookie stores the time of the previous visit. The page shows it, then updates the cookie with the current time.
lastvisit.php
REAL RUN
✍ Try it yourself Also count the total number of visits in a second cookie.
setcookie('visits', (string) ((int) ($_COOKIE['visits'] ?? 0) + 1), ...)
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.
?do=empty -> $cart = []; then $delivery = $total < 200 ? 30 : 0.
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.
TIMEOUT = 15 * 60; minutes left = ceil((TIMEOUT - (time() - $_SESSION['last'])) / 60).
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
Complete PHP 8.3 Course  |  BrainBit Infotech, Ranchi
M12Where is this used in real work?

Uploads and HTTP in real portals

jobs.example.gov.in/apply/documents.php
Step 3: Upload documentsPHP
DocumentRuleStatus
PhotoJPG/PNG, max 200 KB✔ photo_8f3a.jpg
SignatureJPG, max 50 KB✘ too big (180 KB)
Class 10 marksheetPDF, max 1 MBnot uploaded
Behind the screen$_FILES, size and MIME checks, move_uploaded_file, then a JSON status for the progress bar.
📷

Uploads

Admission portals, job applications, KYC and e-commerce sellers all upload photos and PDFs.
📥

Downloads

Receipts, admit cards and reports are generated by PHP and sent as downloads with the right headers.
🔗

Talking to other services

Payment gateways, SMS providers, weather and PIN-code APIs: PHP calls them over HTTP and reads JSON.
Complete PHP 8.3 Course  |  Part 3  |  Uploads, Headers & HTTP
M12Animated explainer

What happens during a file upload

<form method="post" enctype="multipart/form-data">
 <input type="file" name="photo">
📤 Browser sends the file bytes in the POST body
PHP saves it to a temporary file, e.g. C:\xampp\tmp\php3A1.tmp
move_uploaded_file(tmp, 'uploads/photo_8f3a.png')
$_FILES['photo'] = [
 'name' => 'ritu.png',  // from the user: untrusted
 'type' => 'image/png', // from the user: untrusted
 'tmp_name' => '/tmp/php3A1',
 'error' => 0,  // UPLOAD_ERR_OK
 'size' => 1406 ];

Check before keeping it

error = 0? size small enough? extension allowed? real type (finfo) is an image? Then give it a new random name.
If you do nothingPHP deletes the temp file when the request ends. Unchecked uploads are a top way websites get hacked.
Complete PHP 8.3 Course  |  Part 3  |  Uploads, Headers & HTTP
M12Concept

Upload errors and limits

errorConstantMeaning
0UPLOAD_ERR_OKsuccess
1UPLOAD_ERR_INI_SIZEbigger than upload_max_filesize
3UPLOAD_ERR_PARTIALonly part arrived
4UPLOAD_ERR_NO_FILEno file chosen

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.

limits.php
REAL RUN
Complete PHP 8.3 Course  |  Part 3  |  Uploads, Headers & HTTP
M12Concept

header(): talking HTTP

  • header('Location: /thanks.php'); exit; redirect
  • header('Content-Type: application/json'); say what you are sending
  • header('Content-Disposition: attachment; filename="r.txt"'); force a download
  • http_response_code(404); set the status
  • Headers must be sent before any output. Even one space before <?php causes "headers already sent".
CodeMeaning
200 / 201OK / Created
301 / 302moved for ever / for now
400 / 401 / 403 / 404 / 422bad request / login needed / forbidden / not found / invalid data
500server error
status.php
REAL RUN
Complete PHP 8.3 Course  |  Part 3  |  Uploads, Headers & HTTP
M12Practice 1 of 10  •  Easy

Example 1: Upload a profile photo

● 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).
Complete PHP 8.3 Course  |  Part 3  |  Uploads, Headers & HTTP
M12Practice 2 of 10  •  Easy

Example 2: Show upload info

● Easy💼 Real project: Debugging upload problems
Print what PHP received in $_FILES. When an upload "does not work", this is the first thing to look at.
info.php
REAL RUN
✍ Try it yourself Upload a .txt file renamed to .png. What does "Real type" say?
text/plain: the real type comes from the content, not the name.
Complete PHP 8.3 Course  |  Part 3  |  Uploads, Headers & HTTP
M12Practice 3 of 10  •  Easy

Example 3: Redirect after login

● Easy💼 Real project: Sending users to the right page
After login, users go back to the page they wanted (?next=). Only local paths are allowed, otherwise an attacker could redirect users to a fake site.
login.phpfees.phpdashboard.php
REAL RUN
✍ Try it yourself Why is ?next=https://evil.com dangerous? Test it.
It is an "open redirect": a phishing link that starts on your trusted site. The check sends it to /dashboard.php instead.
Complete PHP 8.3 Course  |  Part 3  |  Uploads, Headers & HTTP
M12Practice 4 of 10  •  Easy

Example 4: Download a text receipt

● Easy💼 Real project: "Download receipt" buttons
The Content-Disposition: attachment header makes the browser save the response as a file instead of showing it.
receipt.php
REAL RUN
✍ Try it yourself Make it a CSV download with columns Receipt, Student, Amount.
Content-Type: text/csv and filename="....csv"; write the rows with fputcsv to php://output.
Complete PHP 8.3 Course  |  Part 3  |  Uploads, Headers & HTTP
M12Practice 5 of 10  •  Easy

Example 5: Return JSON

● Easy💼 Real project: Data for mobile apps and JavaScript
A PHP page that answers with JSON instead of HTML: set the content type, then json_encode. Mobile apps and JavaScript fetch() read it.
notices.php
REAL RUN
✍ Try it yourself Support ?limit=1 to return only the latest notice.
array_slice($notices, 0, (int) ($_GET['limit'] ?? count($notices)))
Complete PHP 8.3 Course  |  Part 3  |  Uploads, Headers & HTTP
M12Practice 6 of 10  •  Medium

Example 6: Image upload validation

● 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';
Complete PHP 8.3 Course  |  Part 3  |  Uploads, Headers & HTTP
M12Practice 7 of 10  •  Medium

Example 7: CSV upload and import

● 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.
Complete PHP 8.3 Course  |  Part 3  |  Uploads, Headers & HTTP
M12Practice 8 of 10  •  Medium

Example 8: Custom 404 and 500 pages

● 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.
Complete PHP 8.3 Course  |  Part 3  |  Uploads, Headers & HTTP
M12Practice 9 of 10  •  Hard

Example 9: Call a weather API with cURL

● 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.
Complete PHP 8.3 Course  |  Part 3  |  Uploads, Headers & HTTP
M12Practice 10 of 10  •  Hard

Example 10: Document upload portal

● 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.
Complete PHP 8.3 Course  |  Part 3  |  Uploads, Headers & HTTP
M12Check your understanding

Quick Quiz

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

Q1. Which form attribute is required for uploads?
✔ Without it, only the file name is sent.
Q2. Why check the MIME type with finfo instead of $_FILES[...]['type']?
✔ finfo reads the actual bytes.
Q3. Which status code means "not found"?
✔ 4xx = client problem; 5xx = server problem.
🎯
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  |  Uploads, Headers & HTTP
M12Module summary

Recap: Uploads, Headers & HTTP

What you learned in M12

  • ✔Uploads need POST + enctype="multipart/form-data"; files arrive in $_FILES.
  • ✔Check error code, size, extension and real MIME type; save with a new random name.
  • ✔header() sends redirects, content types and download headers before any output.
  • ✔http_response_code() sets 404, 403, 500 ... so browsers and Google understand.
  • ✔JSON responses: Content-Type application/json + json_encode.
  • ✔cURL or file_get_contents call other APIs; always set a timeout.
🏆

Module 12 complete!

You practised 10 real examples.

👉 Coming next

Part 4, M13 Object-Oriented PHP: classes and objects for students, bank accounts, carts and invoices.
Complete PHP 8.3 Course  |  Part 3  |  Uploads, Headers & HTTP
1 / 1

✎ Code Lab