Review status: Candidate only. TU confirms course identity, but unit outline comes from an unverified third-party source. Do not present it as official TU micro-syllabus. Captured 2026-11-20 from web-technology-2.

Suggested study plan — table of contents (third-party outline, not official TU micro-syllabus)

  • Unit 1: Server-Side Scripting and PHP Fundamentals — 8 hours
    • 1.1 Client-side versus server-side scripting
    • 1.2 Variables, constants and types
    • 1.3 Control structures
    • 1.4 Arrays
    • 1.5 Functions
    • 1.6 Including files and running from the command line
    • 1.7 Seeing the ideas: from request to running PHP
  • Unit 2: Forms, Files, Sessions and Cookies — 7 hours
    • 2.1 Receiving form data
    • 2.2 Validation, sanitising and escaping
    • 2.3 Dates, including files
    • 2.4 File handling
    • 2.5 Cookies
    • 2.6 Sessions
    • 2.7 Sending e-mail
    • 2.8 Seeing the ideas: how data travels between browser and server
  • Unit 3: MySQL for Web Applications — 7 hours
    • 3.1 MySQL basics and data types
    • 3.2 Querying: SELECT, WHERE, ORDER BY
    • 3.3 Updating and deleting
    • 3.4 Aggregate functions, GROUP BY and HAVING
    • 3.5 Subqueries and joins
    • 3.6 Administration notes
    • 3.7 Seeing the ideas: how MySQL stores, filters and joins data
  • Unit 4: Connecting PHP to MySQL — 7 hours
    • 4.1 Connecting and closing
    • 4.2 Running queries: insert, select
    • 4.3 Prepared statements: the only safe way
    • 4.4 Complete CRUD
    • 4.5 PDO, errors and transactions
    • 4.6 Error handling and good practice
    • 4.7 Seeing the ideas: PHP talking to MySQL
  • Unit 5: Object-Oriented Programming in PHP — 7 hours
    • 5.1 Classes, objects, constructors and destructors
    • 5.2 Visibility and encapsulation
    • 5.3 Inheritance, overriding and polymorphism
    • 5.4 Abstract classes, interfaces and traits
    • 5.5 Static members, constants and class methods
    • 5.6 Exceptions
    • 5.7 Seeing the ideas: classes, objects and contracts
  • Unit 6: AJAX, JSON and Web APIs — 6 hours
    • 6.1 JSON in PHP
    • 6.2 A PHP endpoint and a real HTTP request
    • 6.3 AJAX from the browser
    • 6.4 AJAX with PHP and MySQL
    • 6.5 Seeing the ideas: AJAX, JSON and REST
  • Unit 7: Web Application Security and Authentication — 4 hours
    • 7.1 SQL injection
    • 7.2 Cross-site scripting (XSS)
    • 7.3 Cross-site request forgery (CSRF)
    • 7.4 Passwords: hashing, never encryption
    • 7.5 A complete registration and login flow
    • 7.6 A security checklist
    • 7.7 Seeing the ideas: attacks, defences and the three factors
  • Unit 8: Content Management Systems and PHP Frameworks — 4 hours
    • 8.1 What is a CMS?
    • 8.2 The MVC pattern
    • 8.3 Frameworks and tooling
    • 8.4 Seeing the ideas: CMS layers, MVC, hooks, autoloading and deployment

Unit 1: Server-Side Scripting and PHP Fundamentals (8 hrs)

1.1 Client-side versus server-side scripting

Explanation. Client-side scripting runs in the user's browser (HTML, CSS, JavaScript). The browser receives source code and executes it locally, so users can view and modify it. Server-side scripting runs on the web server; the server executes PHP, generates HTML, and sends only the result to the browser. The browser never sees the PHP source, which keeps logic and credentials hidden. A typical web page request goes: browser requests URL → server runs PHP → PHP may read files/database → server returns HTML → browser renders. Server-side scripting is what makes dynamic, personalised, data-driven sites possible.

Worked example. A browser requests https://example.com/greet.php. The server executes PHP that reads the current hour and emits <p>Good morning</p> or <p>Good evening</p>. The browser receives only <p>Good morning</p>; the PHP conditional never reaches the client.

Common mistake. Believing PHP variables are visible in the browser's "View Source." They are not—only the generated HTML is.

Quick self-check. Q: Where does PHP execute? A: On the web server; the browser receives only generated HTML.

1.2 Variables, constants and types

Explanation. PHP variables start with $ and are loosely typed—a variable can hold a string, then a number, without redeclaration. Constants are defined with define() or const and cannot change after definition. Scalar types include string, int, float, bool; compound types include array and object. PHP is case-sensitive for variables ($name ≠ $Name) but not for keywords. Strict typing (declare(strict_types=1);) and type declarations (function add(int $a, int $b): int) reduce bugs.

Worked example.

<?php
define('SITE', 'BCA Portal');
$count = 5;          // int
$count = 'five';     // now string — allowed in loose mode
$price = 19.99;      // float
$active = true;      // bool
echo SITE;           // BCA Portal
// SITE = 'Other';   // Fatal error: constant cannot change
?>

Common mistake. Using define() inside a conditional and expecting it to always exist; define executes at runtime, so the constant may be undefined if the branch is skipped.

Quick self-check. Q: Can a PHP constant be redefined? A: No.

1.3 Control structures

Explanation. PHP supports if/else/elseif, switch, and loops while, do-while, for, foreach. foreach iterates arrays and objects. break exits a loop/switch; continue skips to the next iteration. Comparison uses == (loose, with type juggling) or === (strict, type and value). Prefer === to avoid surprises such as "0" == false being true.

Worked example.

<?php
$score = 85;
if ($score >= 90) {
    $grade = 'A';
} elseif ($score >= 80) {
    $grade = 'B';
} else {
    $grade = 'C';
}
echo $grade; // B
?>

Common mistake. Using a single = (assignment) inside if instead of == or ===, which always evaluates truthy and changes the variable.

Quick self-check. Q: Difference between == and ===? A: == compares after type juggling; === compares type and value strictly.

1.4 Arrays

Explanation. PHP arrays are ordered maps that can act as lists (integer keys) or dictionaries (string keys). Created with [] or array(). Elements accessed by key: $fruits[0]. Useful functions: count(), array_push(), array_pop(), array_keys(), array_values(), in_array(), sort(), ksort(), asort(). Arrays are the universal PHP data structure and are used for form data ($_POST), config, and returned database rows.

Worked example.

<?php
$fruits = ['apple', 'banana', 'cherry'];
$fruits[] = 'date';           // append
echo $fruits[2];              // cherry
echo count($fruits);          // 4
sort($fruits);                // alphabetical
?>

Common mistake. Assuming array keys start at 1; PHP list indices start at 0.

Quick self-check. Q: First index of a PHP list array? A: 0.

1.5 Functions

Explanation. Functions are declared with function name($params) { body } and called by name. Parameters can have default values; arguments may be passed by reference (&) or as variadic (...$args). PHP 8 supports named arguments. Functions return a value with return; without it they return null. Scope: variables inside a function are local unless declared global.

Worked example.

<?php
function tax($amount, $rate = 0.13) {
    return $amount * $rate;
}
echo tax(100);       // 13
echo tax(100, 0.20); // 20
?>

Common mistake. Forgetting return and then wondering why the caller receives null.

Quick self-check. Q: Default return value of a function with no return? A: null.

1.6 Including files and running from the command line

Explanation. include, require, include_once, require_once insert another PHP file's code at that point. require fatal-errors if the file is missing; include only warns. _once variants prevent duplicate inclusion—used for config, functions, headers, footers. PHP can run from the terminal with php file.php; the built-in server php -S localhost:8000 serves files locally without Apache/Nginx, useful for testing.

Worked example.

<?php
require_once 'config.php';   // database credentials
require_once 'header.php';   // page shell
?>
<h1>Welcome</h1>

Terminal: php greet.php or php -S localhost:8000.

Common mistake. Using include (not require) for critical config, so a missing file continues execution with undefined variables.

Quick self-check. Q: Which include stops execution if the file is missing? A: require.

1.7 Seeing the ideas: from request to running PHP

Explanation. This topic ties Unit 1 together: trace one request end to end. User clicks a link or types a URL; DNS resolves the host; the browser sends an HTTP GET to the server; the web server routes .php to the PHP interpreter; PHP runs the script, possibly reading files or databases; output (usually HTML) is sent back as an HTTP response; the browser renders it. Understanding this flow explains why PHP source stays on the server and why dynamic content can differ per user.

Worked example. Request time.php → server runs PHP → echo date('H:i'); → response body 14:30 → browser shows 14:30. Refresh later → different time, same URL, because the server re-runs PHP each time.

Common mistake. Thinking the browser executes PHP and that refreshing guarantees fresh data without a server round trip.

Quick self-check. Q: Does the browser see PHP source? A: No; it sees only the HTML response.


Unit 1 Key Terms

server-side scripting, client-side scripting, variable, constant, type, loose typing, strict typing, control structure, array, function, include, require, command line, built-in server, request, response

Unit 1 Summary

Unit 1 establishes that PHP runs on the server and generates HTML the browser renders. It covers variables/constants/types, control structures, arrays, functions, file inclusion, command-line execution, and the end-to-end request cycle. These are the foundations every later unit builds on.

Unit 2: Forms, Files, Sessions and Cookies (7 hrs)

2.1 Receiving form data

Explanation. HTML forms send data to the server via GET or POST. PHP receives GET data in $_GET and POST data in $_POST; $_REQUEST merges both but is discouraged. Data arrives as strings, so numeric fields need casting. File uploads arrive in $_FILES. Always check a key exists with isset() or $_POST['key'] ?? null before reading, to avoid undefined-index notices.

Worked example. Form:

<form method="post" action="process.php">
  <input name="username">
  <input type="submit">
</form>

process.php: <?php $u = $_POST['username'] ?? ''; echo htmlspecialchars($u); ?>

Common mistake. Reading $_POST['username'] without isset, producing a warning when the field is absent.

Quick self-check. Q: Which superarray holds POST form data? A: $_POST.

2.2 Validation, sanitising and escaping

Explanation. Validation checks data is acceptable (e.g., email format, required fields, age range). Sanitisation cleans data (e.g., filter_var($email, FILTER_SANITIZE_EMAIL)). Escaping makes data safe for a specific output context—htmlspecialchars() for HTML output prevents XSS. Validate on the server (client validation can be bypassed), sanitise before storage, escape on output. Never trust $_GET, $_POST, $_COOKIE, or $_FILES.

Worked example.

<?php
$email = filter_var($_POST['email'] ?? '', FILTER_SANITIZE_EMAIL);
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo htmlspecialchars($email);
} else {
    echo 'Invalid email';
}
?>

Common mistake. Escaping on input instead of on output, which corrupts data for non-HTML uses (CSV, JSON, email).

Quick self-check. Q: Which function escapes output for HTML? A: htmlspecialchars().

2.3 Dates, including files

Explanation. PHP handles dates with date(), time(), strtotime(), and the DateTime/DateTimeZone classes. date('Y-m-d H:i:s') formats the current time; strtotime('+1 week') parses relative dates. Always set a default timezone (date_default_timezone_set() or date.timezone ini) so times are consistent. File inclusion reuses headers/footers/config across pages; put shared HTML in separate files and include them where needed.

Worked example.

<?php
date_default_timezone_set('Asia/Kathmandu');
echo date('Y-m-d H:i:s');   // e.g. 2026-11-20 15:14:27
require_once 'header.php';
?>
<h1>Page</h1>
<?php require_once 'footer.php'; ?>

Common mistake. Storing dates as plain strings instead of consistent UTC or ISO format, causing sorting and timezone bugs.

Quick self-check. Q: Format ISO date in PHP? A: date('Y-m-d H:i:s') (or DateTime).

2.4 File handling

Explanation. PHP reads/writes files with fopen(), fread(), fwrite(), fclose(), or simpler file_get_contents(), file_put_contents(). Modes: r read, w write (truncate), a append. File uploads use <form enctype="multipart/form-data"> and arrive in $_FILES; validate type, size, and name before moving with move_uploaded_file() to a safe folder outside the web root when possible. Check is_uploaded_file() to confirm a genuine upload.

Worked example.

<?php
$content = file_get_contents('notes.txt');
file_put_contents('log.txt', "Entry\n", FILE_APPEND);
// upload:
if (isset($_FILES['file']) && is_uploaded_file($_FILES['file']['tmp_name'])) {
    move_uploaded_file($_FILES['file']['tmp_name'], '/uploads/' . basename($_FILES['file']['name']));
}
?>

Common mistake. Saving uploaded files with their original names into a web-accessible folder, allowing execution of uploaded PHP.

Quick self-check. Q: Which mode appends to a file? A: a.

2.5 Cookies

Explanation. Cookies are small text pieces stored in the browser and sent with every request to the same domain. PHP sets them with setcookie(name, value, expiry, path, domain, secure, httponly) before any output is sent. Read via $_COOKIE. Cookies suit preferences, themes, and remember-me tokens (never passwords). They are limited (~4 KB each), visible to the user, and sent with every request, adding overhead. Mark sensitive cookies HttpOnly and Secure.

Worked example.

<?php
setcookie('theme', 'dark', time() + 60*60*24*30, '/', '', true, true);
echo $_COOKIE['theme'] ?? 'not set';
?>

Common mistake. Calling setcookie() after outputting HTML—headers already sent, so the cookie is not set.

Quick self-check. Q: Where are cookies stored? A: In the user's browser.

2.6 Sessions

Explanation. Sessions store state on the server and identify the user with a random session ID kept in a cookie (PHPSESSID). Start with session_start(); store data in $_SESSION; read it on later requests. Sessions suit login state and shopping carts. Regenerate the session ID after login (session_regenerate_id(true)) to prevent session fixation. Destroy with session_destroy() on logout. Session data lives server-side (default: temp files), so it is not visible to the client.

Worked example.

<?php
session_start();
$_SESSION['user'] = 'sushil';
echo $_SESSION['user'];
session_regenerate_id(true);   // after login
session_destroy();             // logout
?>

Common mistake. Storing passwords or secrets in $_SESSION; store only a user ID and look up the rest from the database.

Quick self-check. Q: Where is session data kept? A: On the server; only the session ID goes to the browser.

2.7 Sending e-mail

Explanation. PHP sends e-mail with mail(to, subject, message, headers). For production use a library (PHPMailer/SwiftMailer) over SMTP because mail() depends on local server configuration and lacks authentication. Always validate recipient addresses and sanitise user input put into headers to prevent header injection. Include From, Content-Type, and charset headers for reliable delivery.

Worked example.

<?php
$to = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
$headers = 'From: noreply@example.com' . "\r\n" .
           'Content-Type: text/plain; charset=UTF-8' . "\r\n";
mail($to, 'Welcome', 'Hello', $headers);
?>

Common mistake. Putting unsanitised user input into e-mail headers, enabling header injection/spoofing.

Quick self-check. Q: Basic PHP mail function? A: mail().

2.8 Seeing the ideas: how data travels between browser and server

Explanation. This topic synthesises Unit 2: data originates in the browser (form fields, cookies, uploads), travels in an HTTP request (URL query for GET, body for POST, cookie headers), is received by PHP in superglobals, validated/sanitised/escaped, possibly stored in files/database/session, and a response (HTML/redirect/JSON) goes back. The key idea: the browser is untrusted; every input must be validated on the server before use.

Worked example. User submits a login form → POST body carries username/password → PHP validates, checks database, sets $_SESSION['user'], sets a remember-me cookie, redirects to dashboard → subsequent requests send the session cookie → server restores state from $_SESSION.

Common mistake. Assuming data arrives intact or honest; attackers can forge requests, cookies, and form fields.

Quick self-check. Q: Are form data and cookies trusted? A: No; always validate on the server.


Unit 2 Key Terms

form, GET, POST, $_GET, $_POST, $_FILES, validation, sanitising, escaping, htmlspecialchars, date, timezone, fopen, file_get_contents, file_put_contents, move_uploaded_file, cookie, setcookie, $_COOKIE, session, session_start, $_SESSION, session_regenerate_id, mail

Unit 2 Summary

Unit 2 covers how PHP receives and handles user data: forms (GET/POST), validation/sanitisation/escaping, dates, file handling and uploads, cookies (client storage), sessions (server storage with a browser ID), and sending e-mail. The theme throughout is that all browser-supplied data is untrusted.

Unit 3: MySQL for Web Applications (7 hrs)

3.1 MySQL basics and data types

Explanation. MySQL is a relational database management system storing data in tables of rows and columns. Each column has a data type. Common types: INT, BIGINT for whole numbers; DECIMAL(m,d) for exact money amounts; VARCHAR(n) for variable-length text; TEXT for long text; DATE, TIME, DATETIME, TIMESTAMP for dates; BOOLEAN/TINYINT(1) for true/false. Constraints: PRIMARY KEY uniquely identifies each row, AUTO_INCREMENT generates ids, NOT NULL requires a value, UNIQUE prevents duplicates, FOREIGN KEY links tables. A database is created with CREATE DATABASE, tables with CREATE TABLE.

Worked example.

CREATE DATABASE IF NOT EXISTS college;
USE college;
CREATE TABLE students (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(100) NOT NULL,
    email VARCHAR(150) UNIQUE NOT NULL,
    gpa DECIMAL(3,2),
    dept VARCHAR(50),
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);

Common mistake. Using FLOAT for money, causing rounding errors; use DECIMAL.

Quick self-check. Q: Type for exact money amounts? A: DECIMAL.

3.2 Querying: SELECT, WHERE, ORDER BY

Explanation. SELECT retrieves columns from a table. SELECT * gets all columns; list specific columns instead. WHERE filters rows using comparisons (=, <>, >, <, LIKE, IN, BETWEEN) and logical operators (AND, OR, NOT). ORDER BY sorts results ascending (ASC, default) or descending (DESC). String matching with LIKE uses % (any sequence) and _ (one character).

Worked example.

SELECT name, email FROM students
WHERE gpa >= 3.5 AND name LIKE 'A%'
ORDER BY name ASC;
-- returns rows where gpa at least 3.5 and name starts with A, sorted by name

Sample row: ('Alina', 'alina@example.com').

Common mistake. SELECT * in production—fetches unused columns and breaks when the schema changes.

Quick self-check. Q: Clause that filters rows? A: WHERE.

3.3 Updating and deleting

Explanation. INSERT adds rows: INSERT INTO table (cols) VALUES (vals). UPDATE changes existing rows: UPDATE table SET col = val WHERE condition—always use WHERE, or every row is updated. DELETE removes rows: DELETE FROM table WHERE condition—without WHERE, the whole table is emptied. TRUNCATE removes all rows faster but cannot be rolled back the same way and resets auto-increment.

Worked example.

INSERT INTO students (name, email, gpa) VALUES ('Bina', 'bina@example.com', 3.8);
UPDATE students SET gpa = 3.9 WHERE id = 2;
DELETE FROM students WHERE id = 5;

Common mistake. Running UPDATE/DELETE without a WHERE clause, modifying or removing every row.

Quick self-check. Q: What happens if UPDATE lacks WHERE? A: All rows are updated.

3.4 Aggregate functions, GROUP BY and HAVING

Explanation. Aggregate functions compute a single value across rows: COUNT(), SUM(), AVG(), MIN(), MAX(). GROUP BY groups rows by one or more columns so aggregates apply per group (e.g., average gpa per department). HAVING filters groups after aggregation (like WHERE but for grouped results); WHERE filters rows before grouping. Order of execution: FROM → WHERE → GROUP BY → HAVING → SELECT → ORDER BY.

Worked example.

SELECT dept, COUNT(*) AS total, AVG(gpa) AS avg_gpa
FROM students
GROUP BY dept
HAVING AVG(gpa) > 3.0
ORDER BY avg_gpa DESC;
-- shows departments with average gpa above 3.0

Common mistake. Using WHERE to filter on an aggregate (e.g., WHERE AVG(gpa) > 3); use HAVING instead.

Quick self-check. Q: Filter groups after aggregation? A: HAVING.

3.5 Subqueries and joins

Explanation. A subquery is a query nested inside another (SELECT ... WHERE id IN (SELECT ...)). Joins combine rows from related tables: INNER JOIN returns matching rows from both; LEFT JOIN returns all rows from the left table plus matches from the right (NULL where none); RIGHT JOIN is the reverse; FULL JOIN (not in MySQL) is both. Join on the primary/foreign key relationship.

Worked example. Tables students(id, name, dept_id) and departments(id, name).

SELECT s.name, d.name AS dept
FROM students s
INNER JOIN departments d ON s.dept_id = d.id;
-- only students with a valid department

SELECT s.name, d.name AS dept
FROM students s
LEFT JOIN departments d ON s.dept_id = d.id;
-- all students, NULL dept if missing

Common mistake. Forgetting the ON condition in a join, which produces a Cartesian product (every row combined with every row).

Quick self-check. Q: Join that keeps all left-table rows? A: LEFT JOIN.

3.6 Administration notes

Explanation. Basic MySQL administration covered here: creating users (CREATE USER), granting privileges (GRANT SELECT, INSERT ON db.* TO 'user'@'host'), changing passwords (ALTER USER ... IDENTIFIED BY), viewing tables (SHOW TABLES), describing a table (DESCRIBE table or SHOW COLUMNS FROM table), checking status (SHOW STATUS), and backing up with mysqldump. Indexes (CREATE INDEX) speed up searches on frequently filtered columns but slow writes slightly.

Worked example.

CREATE USER 'webapp'@'localhost' IDENTIFIED BY 'secret';
GRANT SELECT, INSERT, UPDATE ON college.* TO 'webapp'@'localhost';
SHOW TABLES;
DESCRIBE students;
CREATE INDEX idx_email ON students(email);

Common mistake. Granting ALL PRIVILEGES to the web application user; use least privilege (only needed operations).

Quick self-check. Q: Command to list tables in a database? A: SHOW TABLES.

3.7 Seeing the ideas: how MySQL stores, filters and joins data

Explanation. MySQL stores tables on disk as rows; indexes (often B-trees) let it find rows without scanning the whole table. WHERE uses indexes when available; JOIN matches foreign keys to primary keys across tables; aggregates summarise groups. The relational model means data is normalised into related tables rather than duplicated, keeping it consistent. A web app typically does: connect → query → fetch rows → display HTML → close.

Worked example. A student record lives in students; the department name lives in departments; joining on dept_id displays both together without storing the department name repeatedly.

Common mistake. Duplicating data across tables (denormalisation without reason), causing update anomalies where one copy changes but others do not.

Quick self-check. Q: Benefit of an index? A: Faster row lookups/filtering.


Unit 3 Key Terms

MySQL, table, row, column, INT, VARCHAR, DECIMAL, DATE, DATETIME, PRIMARY KEY, AUTO_INCREMENT, NOT NULL, UNIQUE, FOREIGN KEY, SELECT, WHERE, ORDER BY, INSERT, UPDATE, DELETE, COUNT, SUM, AVG, GROUP BY, HAVING, INNER JOIN, LEFT JOIN, subquery, index, GRANT, mysqldump

Unit 3 Summary

Unit 3 introduces MySQL: data types and constraints, SELECT/WHERE/ORDER BY querying, INSERT/UPDATE/DELETE, aggregate functions with GROUP BY/HAVING, subqueries and joins, and basic administration (users, privileges, indexes, backups). These skills let a PHP web application store and retrieve structured data.

Unit 4: Connecting PHP to MySQL (7 hrs)

4.1 Connecting and closing

Explanation. PHP talks to MySQL through the mysqli extension (procedural or object-oriented) or PDO. A connection needs host, username, password, and database name. With mysqli OO: new mysqli($host, $user, $pass, $db); check $mysqli->connect_error. With PDO: new PDO("mysql:host=$host;dbname=$db", $user, $pass) and set error mode to exceptions (PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION). Close with $mysqli->close() or set PDO to null. Connections are a limited resource; open once and reuse, closing when done (or at script end).

Worked example (PDO).

<?php
$host = 'localhost';
$db   = 'college';
$user = 'webapp';
$pass = 'secret';
try {
    $pdo = new PDO("mysql:host=$host;dbname=$db;charset=utf8mb4", $user, $pass, [
        PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    ]);
    echo 'Connected';
    $pdo = null; // close
} catch (PDOException $e) {
    die('Connection failed: ' . $e->getMessage());
}
?>

Common mistake. Using PDO with default error mode (silent failures) so query errors go unnoticed; always enable exceptions.

Quick self-check. Q: Which PDO attribute makes errors throw exceptions? A: PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION.

4.2 Running queries: insert, select

Explanation. After connecting, run queries with query() (PDO) and fetch results. SELECT returns a result set; fetch rows with fetch() (one row) or fetchAll() (all rows). INSERT returns success; use lastInsertId() to get the new row's auto-increment id. Always fetch into associative arrays (FETCH_ASSOC) so columns are accessed by name.

Worked example.

<?php
// insert
$stmt = $pdo->prepare("INSERT INTO students (name, email, gpa) VALUES (?, ?, ?)");
$stmt->execute(['Bina', 'bina@example.com', 3.8]);
$id = $pdo->lastInsertId();
echo "Inserted id $id";

// select
$rows = $pdo->query("SELECT id, name, gpa FROM students WHERE gpa > 3.5")->fetchAll();
foreach ($rows as $row) {
    echo $row['name'] . ' — ' . $row['gpa'] . "<br>";
}
?>

Common mistake. Fetching with the default mode (FETCH_BOTH) giving both numeric and associative keys, doubling array size and memory use.

Quick self-check. Q: Method to get all rows as associative arrays? A: fetchAll(PDO::FETCH_ASSOC).

4.3 Prepared statements: the only safe way

Explanation. Prepared statements separate SQL structure from data: placeholders (? or :name) are sent to the database first, then values are bound and sent separately. The database never treats data as SQL, which defeats SQL injection. Never build queries by concatenating user input into the SQL string. Prepared statements can also be executed repeatedly with different values efficiently.

Worked example (unsafe vs safe).

<?php
// UNSAFE — do not use:
$bad = $pdo->query("SELECT * FROM students WHERE name = '" . $_GET['name'] . "'");
// If ?name = ' OR '1'='1, all rows leak.

// SAFE:
$stmt = $pdo->prepare("SELECT * FROM students WHERE name = ?");
$stmt->execute([$_GET['name']]);
$row = $stmt->fetch();
?>

Common mistake. Thinking htmlspecialchars() protects SQL; it only protects HTML output. Use prepared statements for SQL.

Quick self-check. Q: Why are prepared statements safe against SQL injection? A: Data is sent separately from SQL and cannot alter the statement structure.

4.4 Complete CRUD

Explanation. CRUD = Create, Read, Update, Delete—the four basic data operations. Create = INSERT; Read = SELECT; Update = UPDATE with a WHERE clause on the primary key; Delete = DELETE with a WHERE clause. A complete web CRUD also includes listing (SELECT with pagination via LIMIT/OFFSET), viewing one row, an edit form pre-filled from the database, and a delete confirmation. Always validate input before writing and escape output before displaying.

Worked example.

<?php
// Create
$pdo->prepare("INSERT INTO students (name, email) VALUES (?, ?)")->execute([$name, $email]);

// Read one
$stmt = $pdo->prepare("SELECT * FROM students WHERE id = ?");
$stmt->execute([$id]); $student = $stmt->fetch();

// Update
$pdo->prepare("UPDATE students SET email = ? WHERE id = ?")->execute([$email, $id]);

// Delete
$pdo->prepare("DELETE FROM students WHERE id = ?")->execute([$id]);

// List with pagination
$page = 1; $perPage = 10;
$offset = ($page - 1) * $perPage;
$rows = $pdo->query("SELECT * FROM students LIMIT $perPage OFFSET $offset")->fetchAll();
?>

Common mistake. Updating/deleting by a non-unique column (e.g., name), affecting multiple rows unintentionally; use the primary key.

Quick self-check. Q: Which clause limits rows for pagination? A: LIMIT (with OFFSET).

4.5 PDO, errors and transactions

Explanation. PDO supports multiple database drivers with one API. Errors: set ATTR_ERRMODE to EXCEPTION so failures throw PDOException, caught with try/catch. Transactions group multiple statements so they succeed or fail together: beginTransaction(), then queries, then commit() or rollBack() on failure. Use transactions for related writes (e.g., transfer money: debit one account, credit another) so partial updates never persist.

Worked example.

<?php
try {
    $pdo->beginTransaction();
    $pdo->prepare("UPDATE accounts SET balance = balance - 100 WHERE id = 1")->execute();
    $pdo->prepare("UPDATE accounts SET balance = balance + 100 WHERE id = 2")->execute();
    $pdo->commit();
    echo 'Transfer complete';
} catch (Exception $e) {
    $pdo->rollBack();
    echo 'Transfer failed: ' . $e->getMessage();
}
?>

Common mistake. Forgetting rollBack() in the catch block, leaving an open transaction that may lock rows.

Quick self-check. Q: Method to make all changes permanent? A: commit(); to undo, rollBack().

4.6 Error handling and good practice

Explanation. Good practice: enable exceptions, never echo raw database errors to users (leaks schema info), log errors server-side and show a generic message, validate all input, use prepared statements everywhere, use least-privilege database users, store credentials outside the web root, close connections, and use UTF-8 (charset=utf8mb4) to support all languages. Wrap database code in try/catch and return HTTP error responses gracefully.

Worked example.

<?php
try {
    $stmt = $pdo->prepare("SELECT * FROM students WHERE id = ?");
    $stmt->execute([$id]);
    $row = $stmt->fetch();
    if (!$row) { http_response_code(404); echo 'Not found'; exit; }
    echo htmlspecialchars($row['name']);
} catch (PDOException $e) {
    error_log($e->getMessage()); // server-side only
    http_response_code(500);
    echo 'Something went wrong';
}
?>

Common mistake. Printing $e->getMessage() directly to the page, exposing table/column names to attackers.

Quick self-check. Q: Where should database error details go? A: Server logs, not the browser.

4.7 Seeing the ideas: PHP talking to MySQL

Explanation. This topic ties Unit 4 together: PHP connects to MySQL, sends SQL, receives result sets, and turns rows into HTML (or JSON). The flow is connect → prepare/execute → fetch → render → close. Prepared statements keep data separate from SQL; transactions keep related writes atomic; error handling keeps failures invisible to users yet logged for developers. This is the core pattern behind every data-driven PHP page.

Worked example. A user views a profile page: PHP connects, SELECT * FROM students WHERE id = ? with the profile id, fetches one row, renders <h1><?php echo htmlspecialchars($row['name']); ?></h1>, then closes.

Common mistake. Opening a new database connection on every page include, exhausting connection limits; share one connection (or use a connection manager).

Quick self-check. Q: Typical PHP/MySQL page flow? A: Connect → query → fetch → render → close.


Unit 4 Key Terms

mysqli, PDO, connection, host, username, password, database, connect_error, PDOException, query, fetch, fetchAll, lastInsertId, prepared statement, placeholder, bind, SQL injection, CRUD, INSERT, SELECT, UPDATE, DELETE, LIMIT, OFFSET, transaction, beginTransaction, commit, rollBack, charset utf8mb4, least privilege

Unit 4 Summary

Unit 4 teaches connecting PHP to MySQL via mysqli/PDO, running SELECT/INSERT queries, using prepared statements as the only safe way to handle user data in SQL, complete CRUD with pagination, PDO error handling with exceptions, transactions for atomic writes, and good practice (credentials, logging, UTF-8, least privilege).

Unit 5: Object-Oriented Programming in PHP (7 hrs)

5.1 Classes, objects, constructors and destructors

Explanation. A class is a blueprint; an object is an instance. Declare with class Student { }, create with new Student(). Properties hold state; methods hold behaviour. The constructor __construct() runs when an object is created—use it to initialise properties (PHP 8 supports constructor promotion). The destructor __destruct() runs when the object is destroyed—use for cleanup. Objects are accessed with ->; static members with ::.

Worked example.

<?php
class Student {
    public string $name;
    public float $gpa;

    public function __construct(public string $name, public float $gpa = 0.0) {}

    public function detail(): string {
        return "$this->name — GPA $this->gpa";
    }
}

$s = new Student('Alina', 3.8);
echo $s->detail(); // Alina — GPA 3.8
?>

Common mistake. Accessing $this inside a static method—static context has no $this.

Quick self-check. Q: Method that runs automatically when an object is created? A: __construct().

5.2 Visibility and encapsulation

Explanation. Visibility modifiers control access: public (anywhere), protected (class and subclasses), private (only the class). Encapsulation hides internal state and exposes behaviour through methods, so the object's data stays consistent. Use getters/setters to validate before changing properties. Without encapsulation, external code can put an object into an invalid state.

Worked example.

<?php
class Account {
    private float $balance = 0.0;

    public function deposit(float $amount): void {
        if ($amount > 0) $this->balance += $amount;
    }

    public function getBalance(): float {
        return $this->balance;
    }
}

$a = new Account();
// $a->balance = -500; // Error: private
$a->deposit(100);
echo $a->getBalance(); // 100
?>

Common mistake. Making all properties public, which breaks encapsulation and lets external code bypass validation.

Quick self-check. Q: Modifier restricting access to the class itself? A: private.

5.3 Inheritance, overriding and polymorphism

Explanation. Inheritance lets a class extend another (class Graduate extends Student), inheriting public/protected members and adding or overriding methods. Overriding redefines a parent method in the child. Polymorphism lets code work with objects of different subclasses through a common interface—e.g., a loop calling detail() on Student and Graduate objects, each producing its own result.

Worked example.

<?php
class Person {
    public function say(): string { return 'Hello'; }
}
class Student extends Person {
    public function say(): string { return 'Hello, I am a student'; }
}

function greet(Person $p): void { echo $p->say(); }
greet(new Person());      // Hello
greet(new Student());     // Hello, I am a student
?>

Common mistake. Forgetting parent::__construct() in a child constructor, so parent properties are never initialised.

Quick self-check. Q: Keyword for inheritance in PHP? A: extends.

5.4 Abstract classes, interfaces and traits

Explanation. An abstract class cannot be instantiated and may contain abstract methods (no body) that subclasses must implement. An interface (interface) declares a contract of public methods only; a class implements an interface and must define all its methods. A trait (trait) reuses methods across classes without inheritance (PHP supports single inheritance only; traits solve code reuse across unrelated classes). A class can implement multiple interfaces and use multiple traits.

Worked example.

<?php
interface Payable {
    public function pay(float $amount): bool;
}

abstract class User {
    public function __construct(public string $name) {}
    abstract public function role(): string;
}

class Student extends User implements Payable {
    public function role(): string { return 'student'; }
    public function pay(float $amount): bool { return true; }
}

$s = new Student('Alina');
echo $s->role() . ' paid: ' . ($s->pay(50) ? 'yes' : 'no');
?>

Common mistake. Trying to instantiate an abstract class directly—fatal error.

Quick self-check. Q: Can a class implement multiple interfaces? A: Yes.

5.5 Static members, constants and class methods

Explanation. static properties/methods belong to the class, not an instance—accessed with ClassName::$prop or ClassName::method(), or self::/static:: inside the class. Constants (const) are fixed values on the class. Static members are shared across all instances; useful for counters, configuration, or factory methods. self:: binds to the class where written; static:: (late static binding) respects the actual called class in inheritance.

Worked example.

<?php
class Counter {
    public static int $count = 0;
    public const PREFIX = 'ID';

    public function __construct() { self::$count++; }
    public static function total(): int { return self::$count; }
}

new Counter(); new Counter();
echo Counter::PREFIX . Counter::total(); // ID2
?>

Common mistake. Using $this-> to access a static property inside an instance method—works but is confusing; use self::$prop.

Quick self-check. Q: Access a static method without creating an object? A: ClassName::method().

5.6 Exceptions

Explanation. Exceptions represent errors (try { ... } catch (Exception $e) { ... }). throw new Exception('message') raises one; catch handles it; finally runs regardless. Custom exception classes extend Exception. Exceptions make error paths explicit instead of returning error codes or silent failures. In OOP, invalid operations (e.g., withdrawing more than the balance) should throw exceptions.

Worked example.

<?php
class InsufficientFunds extends Exception {}

class Wallet {
    private float $balance;
    public function __construct(float $balance) { $this->balance = $balance; }
    public function withdraw(float $amount): void {
        if ($amount > $this->balance) {
            throw new InsufficientFunds('Not enough money');
        }
        $this->balance -= $amount;
    }
}

try {
    (new Wallet(10))->withdraw(100);
} catch (InsufficientFunds $e) {
    echo 'Error: ' . $e->getMessage();
}
?>

Common mistake. Catching the broad Exception and swallowing errors without logging or rethrowing, hiding bugs.

Quick self-check. Q: Block that always runs even after an exception? A: finally.

5.7 Seeing the ideas: classes, objects and contracts

Explanation. Unit 5 ties OOP together: classes bundle state and behaviour into objects; visibility and encapsulation protect state; inheritance and polymorphism let related classes vary behaviour through a shared type; abstract classes and interfaces define contracts; traits reuse code; static members hold class-level data; exceptions make failures explicit. Together these let a PHP application grow large while staying organised and maintainable.

Worked example. A payment system: Payable interface defines pay(); Student and Staff implement it differently; code loops over a list of Payable objects calling pay() without knowing each concrete type.

Common mistake. Using inheritance for code reuse alone instead of for "is-a" relationships; prefer traits or composition when there is no true is-a link.

Quick self-check. Q: What defines a contract a class must fulfil? A: An interface (or abstract class).


Unit 5 Key Terms

class, object, instance, constructor, __construct, destructor, __destruct, property, method, visibility, public, protected, private, encapsulation, getter, setter, inheritance, extends, overriding, polymorphism, abstract class, interface, implements, trait, static, const, self, static::, exception, throw, try, catch, finally

Unit 5 Summary

Unit 5 covers object-oriented PHP: classes/objects, constructors/destructors, visibility and encapsulation, inheritance/overriding/polymorphism, abstract classes/interfaces/traits, static members and constants, and exceptions. These tools structure larger PHP applications into reusable, maintainable components.

Unit 6: AJAX, JSON and Web APIs (6 hrs)

6.1 JSON in PHP

Explanation. JSON (JavaScript Object Notation) is a text format for data, widely used between PHP and browsers or APIs. PHP converts PHP values to JSON with json_encode() and parses JSON into PHP values with json_decode(). json_decode($json, true) returns an associative array; without true, it returns objects. Always check json_last_error() after decoding. JSON supports objects, arrays, strings, numbers, booleans, and null.

Worked example.

<?php
$data = ['name' => 'Alina', 'gpa' => 3.8, 'active' => true];
$json = json_encode($data); // {"name":"Alina","gpa":3.8,"active":true}
echo $json;

$decoded = json_decode($json, true);
echo $decoded['name']; // Alina

if (json_last_error() !== JSON_ERROR_NONE) {
    echo 'Invalid JSON';
}
?>

Common mistake. Passing json_decode output as an object ($decoded->name) when true was not passed, or vice versa—know which you asked for.

Quick self-check. Q: Function to turn a PHP array into JSON? A: json_encode().

6.2 A PHP endpoint and a real HTTP request

Explanation. A PHP endpoint is a URL that returns data (usually JSON) instead of a full page. It reads input ($_GET, $_POST, or php://input for raw bodies like JSON PUT/POST), validates it, performs work (database, files), sets headers (Content-Type: application/json), and outputs json_encode(). HTTP methods: GET reads, POST creates, PUT updates, DELETE deletes. Status codes: 200 OK, 201 Created, 400 Bad Request, 404 Not Found, 500 Server Error.

Worked example.

<?php
header('Content-Type: application/json');
$id = $_GET['id'] ?? null;
if (!$id) { http_response_code(400); echo json_encode(['error' => 'id required']); exit; }
$stmt = $pdo->prepare("SELECT name, gpa FROM students WHERE id = ?");
$stmt->execute([$id]);
$row = $stmt->fetch();
if (!$row) { http_response_code(404); echo json_encode(['error' => 'not found']); exit; }
echo json_encode(['status' => 'ok', 'data' => $row]);
?>

Common mistake. Forgetting header('Content-Type: application/json'), so browsers/clients may not parse the response as JSON.

Quick self-check. Q: Header that tells the client the body is JSON? A: Content-Type: application/json.

6.3 AJAX from the browser

Explanation. AJAX (Asynchronous JavaScript and XML) lets a browser send HTTP requests in the background without reloading the page, then update part of the page with the response. Modern browsers use fetch() (returns a Promise). Older code used XMLHttpRequest or jQuery $.ajax. The response is usually JSON; parse with response.json() and insert into the DOM. Handle errors with .catch() and check response.ok.

Worked example.

<script>
fetch('/api/student.php?id=2')
  .then(r => { if (!r.ok) throw new Error('bad'); return r.json(); })
  .then(data => { document.getElementById('out').textContent = data.data.name; })
  .catch(err => { console.error(err); });
</script>
<div id="out">Loading...</div>

Common mistake. Inserting raw API text into the page without escaping, causing XSS; escape or use textContent.

Quick self-check. Q: Browser API for background HTTP requests? A: fetch().

6.4 AJAX with PHP and MySQL

Explanation. Combine the previous topics: the browser sends fetch() to a PHP endpoint; PHP uses prepared statements to query MySQL safely; returns JSON; the browser updates the page. Example: a search box that lists matching students as you type, or a live comment system. The PHP endpoint validates input, runs a prepared SELECT with LIKE, fetches rows, and returns json_encode($rows).

Worked example. PHP endpoint (search.php):

<?php
header('Content-Type: application/json');
$q = '%' . ($_GET['q'] ?? '') . '%';
$stmt = $pdo->prepare("SELECT id, name FROM students WHERE name LIKE ? LIMIT 10");
$stmt->execute([$q]);
echo json_encode($stmt->fetchAll());
?>

Browser:

fetch('search.php?q=' + encodeURIComponent('Ali'))
  .then(r => r.json())
  .then(rows => console.log(rows));

Common mistake. Sending raw user input into the LIKE query without a prepared statement—SQL injection through search.

Quick self-check. Q: Safe way to use user text in a MySQL LIKE query? A: Prepared statement with ? placeholder.

6.5 Seeing the ideas: AJAX, JSON and REST

Explanation. AJAX + JSON let web pages behave like applications: partial updates, no full reloads. REST (Representational State Transfer) is a style where URLs represent resources (e.g., /students/2) and HTTP methods represent actions (GET read, POST create, PUT update, DELETE delete). JSON is the usual body format. Statelessness: each request contains all info needed; the server does not rely on remembering prior requests beyond sessions. This unit shows how PHP serves data and browsers consume it asynchronously.

Worked example. REST-style: GET /api/students lists all; POST /api/students creates one; GET /api/students/5 reads one; PUT /api/students/5 updates; DELETE /api/students/5 removes. Each returns JSON with a proper status code.

Common mistake. Using GET for actions that change data (e.g., ?delete=1), which browsers/crawlers can trigger accidentally—use POST/DELETE for state changes.

Quick self-check. Q: HTTP method to create a resource in REST? A: POST.


Unit 6 Key Terms

JSON, json_encode, json_decode, json_last_error, endpoint, HTTP method, GET, POST, PUT, DELETE, status code, Content-Type, application/json, php://input, AJAX, fetch, Promise, XMLHttpRequest, DOM, REST, resource, stateless, prepared statement, LIKE, XSS

Unit 6 Summary

Unit 6 covers JSON encoding/decoding in PHP, building PHP endpoints that return JSON with correct headers and status codes, calling them from the browser with AJAX (fetch), combining AJAX with PHP and MySQL using prepared statements, and the REST ideas of resources, HTTP methods, and stateless JSON APIs.

Unit 7: Web Application Security and Authentication (4 hrs)

7.1 SQL injection

Explanation. SQL injection happens when user input is concatenated directly into a SQL query, letting an attacker change the statement's meaning. Example: a login query SELECT * FROM users WHERE username = '$user' with input admin' -- comments out the password check and logs in as admin without a password. Defences: use prepared statements with placeholders (the primary defence), validate input, apply least-privilege database accounts, and never echo raw database errors. htmlspecialchars() does NOT stop SQL injection—it only protects HTML output.

Worked example.

<?php
// UNSAFE:
$pdo->query("SELECT * FROM users WHERE username = '" . $_POST['user'] . "'");
// Input: admin' --  → bypasses password

// SAFE (prepared statement):
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = ?");
$stmt->execute([$_POST['user']]);
$user = $stmt->fetch();
?>

Common mistake. Believing escaping or validation alone is enough; prepared statements are the reliable defence.

Quick self-check. Q: Primary defence against SQL injection? A: Prepared statements with placeholders.

7.2 Cross-site scripting (XSS)

Explanation. XSS lets an attacker inject malicious JavaScript into a page viewed by other users. It happens when untrusted data is inserted into HTML without escaping: <div><?php echo $_GET['q']; ?></div> with input <script>stealCookies()</script> executes in victims' browsers. Types: reflected (from request, e.g., search term echoed back), stored (saved in database, e.g., a comment), and DOM-based (client-side). Defence: escape output with htmlspecialchars($data, ENT_QUOTES, 'UTF-8') for HTML, use htmlspecialchars in attribute contexts too, set Content-Security-Policy headers, and use textContent instead of innerHTML in JavaScript.

Worked example.

<?php
// UNSAFE: echo $_GET['q'];
// SAFE:
echo htmlspecialchars($_GET['q'] ?? '', ENT_QUOTES, 'UTF-8');
?>

Common mistake. Escaping on input (before storage) instead of on output, which breaks non-HTML uses of the same data.

Quick self-check. Q: Function to escape output for HTML? A: htmlspecialchars().

7.3 Cross-site request forgery (CSRF)

Explanation. CSRF tricks a logged-in user's browser into sending an unwanted request to a site where they are authenticated, because the browser automatically attaches cookies. Example: an img tag pointing to example.com/delete.php?id=5 while the user is logged in deletes their record. Defence: include an unpredictable CSRF token in each state-changing form (hidden field) and verify it on the server; use SameSite=Strict/Lax cookies; require re-authentication for sensitive actions; never perform state changes via GET.

Worked example.

<?php
session_start();
if (empty($_SESSION['csrf'])) $_SESSION['csrf'] = bin2hex(random_bytes(32));
// form includes: <input type="hidden" name="csrf" value="<?= htmlspecialchars($_SESSION['csrf']) ?>">
if ($_POST['csrf'] ?? '' !== $_SESSION['csrf']) {
    http_response_code(403); exit('Invalid CSRF token');
}
?>

Common mistake. Validating the token only on some forms or comparing with == (loose) instead of strict comparison/hash_equals.

Quick self-check. Q: Why does CSRF work? A: The browser automatically sends the user's cookies with cross-origin requests.

7.4 Passwords: hashing, never encryption

Explanation. Passwords must never be stored in plain text or reversible encryption. PHP provides password_hash($password, PASSWORD_DEFAULT) which uses bcrypt (slow salted hash) with an automatic random salt, and password_verify($password, $hash) to check. Encryption is reversible (bad for passwords); hashing is one-way. PASSWORD_DEFAULT may change to a stronger algorithm over time, so store the full hash output (it includes algorithm, cost, and salt) in a VARCHAR(255) column.

Worked example.

<?php
$hash = password_hash($_POST['password'], PASSWORD_DEFAULT);
// store $hash in users.password column (VARCHAR 255)
// later, at login:
if (password_verify($_POST['password'], $row['password'])) {
    // login OK
} else {
    // invalid
}
?>

Common mistake. Using md5() or sha1() (fast, unsalted, crackable) or encrypt()/openssl_encrypt() (reversible) for passwords.

Quick self-check. Q: PHP function to hash a password? A: password_hash(); to check, password_verify().

7.5 A complete registration and login flow

Explanation. Registration: validate input (required, email format, unique email, strong password), hash the password with password_hash, insert via prepared statement, generic success message (do not reveal whether email exists). Login: look up user by email, password_verify, on success session_regenerate_id(true) to prevent session fixation, store only user id in $_SESSION, give generic failure messages (do not say whether email or password was wrong). Logout: $_SESSION = []; session_destroy(); and clear the session cookie. Use HTTPS so cookies/session IDs are not intercepted.

Worked example.

<?php
// register
$hash = password_hash($_POST['password'], PASSWORD_DEFAULT);
$stmt = $pdo->prepare("INSERT INTO users (email, password) VALUES (?, ?)");
$stmt->execute([$_POST['email'], $hash]);

// login
$stmt = $pdo->prepare("SELECT * FROM users WHERE email = ?");
$stmt->execute([$_POST['email']]); $u = $stmt->fetch();
if ($u && password_verify($_POST['password'], $u['password'])) {
    session_start();
    session_regenerate_id(true);
    $_SESSION['user_id'] = $u['id'];
    header('Location: dashboard.php'); exit;
} else {
    echo 'Invalid credentials'; // generic
}
?>

Common mistake. Revealing "email not found" vs "wrong password", enabling email enumeration.

Quick self-check. Q: Why regenerate the session ID after login? A: To prevent session fixation attacks.

7.6 A security checklist

Explanation. Apply a checklist to every form, query, and output: validate all input server-side; escape all output for its context; use prepared statements for SQL; hash passwords (never encrypt/plain); use CSRF tokens on state-changing forms; use HTTPS with Secure/HttpOnly/SameSite cookies; regenerate session ID after login; use least-privilege database accounts; keep PHP and libraries updated; log errors server-side only; set security headers (Content-Security-Policy, X-Content-Type-Options). Security is a continuous practice, not a feature added at the end.

Worked example. Checklist applied to a comment form:

  1. Validate name/comment present and length-limited.
  2. CSRF token verified.
  3. INSERT via prepared statement.
  4. On display, htmlspecialchars(comment).
  5. Session cookie Secure/HttpOnly/SameSite.
  6. HTTPS enforced.

Common mistake. Treating the checklist as one-time setup instead of reviewing every new feature.

Quick self-check. Q: Is security a one-time setup or ongoing practice? A: Ongoing practice applied to every feature.

7.7 Seeing the ideas: attacks, defences and the three factors

Explanation. The three factors of authentication are: something you know (password), something you have (phone/token), something you are (biometric). Unit 7's attacks—SQL injection, XSS, CSRF—all stem from trusting input; their defences (prepared statements, output escaping, CSRF tokens) restore that trust boundary. Password hashing and the registration/login flow protect stored credentials. Authentication verifies identity (who you are); authorisation verifies permission (what you may do). Both are needed for secure web applications.

Worked example. A user logs in (authentication: password) then tries to edit another user's profile; the app checks ownership (authorisation) and rejects it.

Common mistake. Confusing authentication with authorisation; logging in does not grant access to all data.

Quick self-check. Q: What do SQL injection, XSS, and CSRF have in common? A: All arise from trusting untrusted input.


Unit 7 Key Terms

SQL injection, prepared statement, placeholder, XSS, cross-site scripting, htmlspecialchars, ENT_QUOTES, CSRF, cross-site request forgery, CSRF token, SameSite, password_hash, password_verify, bcrypt, salt, session_regenerate_id, authentication, authorisation, HTTPS, Secure, HttpOnly, Content-Security-Policy, security checklist

Unit 7 Summary

Unit 7 covers web application security: SQL injection (defended with prepared statements), XSS (defended with output escaping), CSRF (defended with tokens and cookie flags), password hashing with password_hash/password_verify (never encryption), a complete registration/login flow with session regeneration and generic messages, and a security checklist applied to every form, query, and output. Authentication and authorisation are distinguished.

Unit 8: Content Management Systems and PHP Frameworks (4 hrs)

8.1 What is a CMS?

Explanation. A content management system (CMS) lets non-programmers create, edit, and publish content through an admin interface without writing code. Examples: WordPress, Joomla, Drupal. A CMS stores content (posts, pages, media) in a database (typically MySQL) and renders it via themes/templates. It provides plugins/extensions for extra features, user roles, and an admin dashboard. CMSs are built with PHP and MySQL; they are quick to deploy but can be slower and less flexible than custom code, and popular CMSs are frequent attack targets, so updates and security matter.

Worked example. WordPress flow: admin writes a post in the dashboard → stored in wp_posts table → theme template single.php fetches the post by id and renders HTML → visitor sees the page.

Common mistake. Assuming a CMS requires no maintenance; plugins/themes/core must be kept updated for security.

Quick self-check. Q: Where does a CMS typically store content? A: In a database (usually MySQL).

8.2 The MVC pattern

Explanation. MVC (Model-View-Controller) separates an application into three concerns. Model: data and business logic (database queries, validation). View: presentation (HTML templates, what the user sees). Controller: handles input, talks to the model, chooses the view. A router maps URLs to controller actions. Benefits: separation of concerns, easier testing, reusable views, multiple controllers sharing models. Frameworks like Laravel, Symfony, and CodeIgniter implement MVC.

Worked example. Request /students/5: router → StudentController@show(5) → controller calls Student::find(5) (model) → passes result to show.php view → view renders <h1><?php echo $student->name; ?></h1>.

Common mistake. Putting database queries directly in the view, breaking separation and making testing hard.

Quick self-check. Q: Which MVC part handles user input and chooses the view? A: Controller.

8.3 Frameworks and tooling

Explanation. PHP frameworks (Laravel, Symfony, CodeIgniter, Yii) provide routing, database abstraction (ORM/Query Builder), templating (Blade, Twig), authentication scaffolding, validation, and testing tools. Tooling includes Composer (dependency management), PSR autoloading, PHPUnit (testing), and static analysis. Autoloading (spl_autoload_register or Composer PSR-4) loads classes automatically instead of manual require. Deployment adds HTTPS (TLS certificate), secure config (env files outside web root), backups, and process supervision.

Worked example. Composer composer require laravel/framework; autoloading maps App\Models\Student to app/Models/Student.php automatically via PSR-4; .env holds DB_PASSWORD outside the web root.

Common mistake. Committing .env with real secrets to version control; use environment variables and example files only.

Quick self-check. Q: PHP dependency manager? A: Composer.

8.4 Seeing the ideas: CMS layers, MVC, hooks, autoloading and deployment

Explanation. This topic synthesises Unit 8: a CMS layers content (database), presentation (themes), and extension (plugins/hooks). MVC provides the structure inside frameworks: routes → controllers → models → views. Hooks let plugins run code at certain points without editing core. Autoloading loads classes on demand. Deployment moves the app to a server with HTTPS, secure configuration, and backups. Together these explain how modern PHP applications and content platforms are built, extended, and run in production.

Worked example. A WordPress plugin hooks into the_content to add a footer to every post; a Laravel app routes /posts to PostController@index, which queries the Post model and renders a Blade view; deployed with HTTPS and nightly database backups.

Common mistake. Editing CMS core files instead of using hooks/plugins—changes are lost on update.

Quick self-check. Q: What loads classes automatically in modern PHP? A: Autoloading (Composer PSR-4).


Unit 8 Key Terms

CMS, content management system, WordPress, Joomla, theme, template, plugin, extension, admin dashboard, database, MVC, model, view, controller, router, framework, Laravel, Symfony, Composer, autoloading, PSR-4, ORM, Blade, Twig, HTTPS, .env, deployment, backup, hook

Unit 8 Summary

Unit 8 covers content management systems (what a CMS is, themes/templates, plugins, admin panel, PHP/MySQL), the MVC pattern (model/view/controller/router), frameworks and tooling (Composer, autoloading, ORM, templating, testing), and deployment (HTTPS, secure config, backups). The synthesis topic ties CMS layers, MVC, hooks, autoloading, and deployment together.

Practice questions and answers — Units 1–3

Q1. Where does PHP execute, and what does the browser receive? A1. On the web server. The browser receives only the generated HTML response; PHP source is never sent to the client.

Q2. What is the difference between include and require? A2. require produces a fatal error and stops execution if the file is missing; include emits a warning and continues.

Q3. Which PHP superarray holds data sent via POST? A3. $_POST.

Q4. Which function escapes output for safe HTML display? A4. htmlspecialchars().

Q5. Where is session data stored, and what is sent to the browser? A5. Session data is stored on the server; only the session ID (cookie) is sent to the browser.

Q6. What SQL type should be used for exact monetary amounts? A6. DECIMAL(m,d)—not FLOAT.

Q7. Write a query listing students with gpa above 3.5 ordered by name descending. A7. SELECT name, gpa FROM students WHERE gpa > 3.5 ORDER BY name DESC;

Q8. What is the difference between WHERE and HAVING? A8. WHERE filters rows before grouping; HAVING filters groups after aggregation.

Q9. Which join returns all rows from the left table even without a match? A9. LEFT JOIN.

Q10. What is the danger of UPDATE or DELETE without WHERE? A10. Every row in the table is modified or removed.


Practice questions and answers — Units 4–6

Q1. Which two PHP extensions connect to MySQL? A1. mysqli and PDO.

Q2. What does PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION do? A2. Makes PDO throw exceptions on errors instead of failing silently.

Q3. Why are prepared statements safe against SQL injection? A3. SQL structure and data are sent separately; user data cannot change the statement.

Q4. Name the four CRUD operations. A4. Create (INSERT), Read (SELECT), Update (UPDATE), Delete (DELETE).

Q5. Which method makes transaction changes permanent? A5. commit() (undo with rollBack()).

Q6. Which keyword inherits from a parent class in PHP? A6. extends.

Q7. Which visibility modifier restricts access to the class itself? A7. private.

Q8. Can a PHP class implement multiple interfaces? A8. Yes.

Q9. Which PHP function turns an array into JSON? A9. json_encode().

Q10. Which browser function sends background HTTP requests? A10. fetch().


Practice questions and answers — Units 7–8

Q1. What is the primary defence against SQL injection? A1. Prepared statements with placeholders (user data never becomes SQL).

Q2. Which PHP function escapes output for HTML to prevent XSS? A2. htmlspecialchars().

Q3. Why should passwords never be encrypted for storage? A3. Encryption is reversible; use one-way salted hashes (password_hash).

Q4. What does session_regenerate_id(true) prevent after login? A4. Session fixation attacks.

Q5. Give one CSRF defence. A5. Unpredictable CSRF token verified on the server (also SameSite cookies).

Q6. What does a CMS store content in? A6. A database, typically MySQL.

Q7. Which MVC component handles input and chooses the view? A7. Controller.

Q8. What is Composer used for in PHP? A8. Dependency management and PSR-4 autoloading.

Q9. Name two deployment requirements for a PHP app. A9. HTTPS (TLS) and secure configuration/backups.

Q10. Why not edit CMS core files? A10. Changes are lost when the CMS is updated; use hooks/plugins instead.